# amber.py
#

from Tkinter import *
from tkFileDialog import *
from pymol import cmd, stored, util
from pymol.wizard import Wizard

import tkSimpleDialog
import tkMessageBox
import os
import sys
import math
import shutil
import subprocess

import colorsys,re

import Tkinter,Pmw
import Pmw

monitor_list = []


#######################################################################################
def __init__(self):
	cmd.set("retain_order", 1)
	cmd.set("pdb_use_ter_records", 1)
	read_settings(self)

	cmd.set('retain_order',1)
	cmd.set('pdb_use_ter_records',1)
        cmd.set('pdb_conect_all', 0)
	cmd.set('sphere_scale',0.5)

	g_save_project = 0

	# Simply add the menu entry and callback
	self.menuBar.addmenu('Amber', 'Molecular Mechanics',tearoff=TRUE)
	self.menuBar.addmenuitem('Amber', 'command', 'Use Reduce to optimize ASN,GLN,HIS conformations/protonation states',
				label = 'Use Reduce to optimize ASN,GLN,HIS conformations/protonation states',command = lambda s=self : use_reduce(s))
	self.menuBar.addmenuitem('Amber', 'command', 'Modify HIS state manually',
				label = 'Modify HIS state manually',command = lambda s=self : modify_his_state(s, 'sele'))
	self.menuBar.addmenuitem('Amber', 'command', 'Identify water molecules with certain properties',
				label = 'Remove waters',command = lambda s=self : remove_waters(s))
	self.menuBar.addmenuitem('Amber', 'command', 'Add hydrogens',
				label = 'Prepare protein',command = lambda s=self : add_hydrogens(s))
    
#        self.menuBar.addmenuitem('Amber', 'separator')

#        self.menuBar.addmenuitem('Amber', 'command', 'convert .gro file (AMBER force field) to .pdb file (for AMBER program)',
#				label = 'Convert: GROMACS --&gt; AMBER',command = lambda s=self : convert_gro_pdb(s))

        self.menuBar.addmenuitem('Amber', 'separator')

        self.menuBar.addmenuitem('Amber', 'command', 'minimize_ligand',
				label = 'Minimize (AMBER, interactive)',command = lambda s=self : minim_lig_prot(s))
	self.menuBar.addmenuitem('Amber', 'command', 'md_simulation',
				label = 'Molecular mechanics for protein-ligand complex(AMBER, background)',command = lambda s=self : md_simulation(s, 'amber'))
	self.menuBar.addmenuitem('Amber', 'command', 'md_simulation',
				label = 'Molecular mechanics for protein (AMBER, background)',command = lambda s=self : md_simulation_protein(s, 'amber'))
#	self.menuBar.addmenuitem('Amber', 'command', 'md_simulation',
#				label = 'Molecular mechanics (GROMACS, background)',command = lambda s=self : md_simulation(s, 'gromacs'))
	self.menuBar.addmenuitem('Amber', 'command', 'md_simulation',
				label = 'Monitor/Read molecular mechanics results',command = lambda s=self : md_import(s))
    
        self.menuBar.addmenuitem('Amber', 'separator')
	self.menuBar.addmenuitem('Amber', 'command', 'SIE',
				label = 'Calculate free energy (SIE, AMBER only)',command = lambda s=self : calculate_SIE(s))
#	self.menuBar.addmenuitem('Amber', 'command', 'MMPBSA',
#				label = 'Calculate free energy (MM/PBSA)',command = lambda s=self : calculate_MMPBSA(s))
        self.menuBar.addmenuitem('Amber', 'command', 'Color by b-factor',
				label = 'Color by b-factor',command = lambda s=self : color_by_bfactor(s))
#        self.menuBar.addmenuitem('MM', 'command', 'Compute residues\' b-factor',
#				label = 'Compute residues\' b-factor',command = lambda s=self : compute_bfactor(s))

        
        self.menuBar.addmenuitem('Amber', 'separator')

        self.menuBar.addmenuitem('Amber', 'command', 'Write selected objects as mol2',
				label = 'Write individual ligand object as mol2',command = lambda s=self : write_mol2_select(s))

	self.menuBar.addmenuitem('Amber', 'separator')

	self.menuBar.addmenuitem('Amber', 'command', 'Modify Settings_Linux.txt',
				label = 'Modify Settings_Linux.txt file',command = lambda s=self : modify_settings(s))

#######################################################################################
class his_dialog(tkSimpleDialog.Dialog):
    def body(self, master):
#        self.prompt = [ 'Please click on the first atom...']
        self.ok_flag = 0

        Label(master, text='Select histidine state for selected residue', font=('Helvetica', '14')).grid(row=0, column=0, sticky=N)

        
        self.v0 = StringVar()
        self.rb_his0 = Radiobutton(master, text='HIE (N_epsilon protonated)', variable=self.v0, value='HIE')
        self.rb_his0.grid(row=1, column=0, sticky=W)
        self.rb_his1 = Radiobutton(master, text='HID (N_delta protonated)', variable=self.v0, value='HID')
        self.rb_his1.grid(row=2, column=0, sticky=W)
        self.rb_his2 = Radiobutton(master, text='HIP (both N protonated)', variable=self.v0, value='HIP')
        self.rb_his2.grid(row=3, column=0, sticky=W)
        self.rb_his0.select()
        
    def validate(self):
        try:
            return 1

        except ValueError:
            tkMessageBox.showwarning(
                'Bad input',
                'Illegal values, please try again'
            )
            return 0

    def apply(self):
        self.ok_flag = 1

    def cancel(self, event=None):
        # put focus back to the parent window
        self.parent.focus_set()
        self.destroy()

#######################################################################################
class specifyWater_dialog(tkSimpleDialog.Dialog):
    def body(self, master):
        self.ok_flag = 0

        Label(master, text='Remove water molecules if ...', font=('Helvetica', '14')).grid(row=0, columnspan=2, sticky=N)
        Label(master, text='  ').grid(row=1, columnspan=2, sticky=N)

        Label(master, text='  ').grid(row=10, columnspan=3, sticky=N)
        Label(master, text='Number of hydrogen bonds', relief='sunken', width=70, pady=4).grid(row=11, columnspan=3, sticky=N)

        Label(master, text='with protein  &lt; ').grid(row=12, sticky=W)
	self.e1 = Entry(master, width=5)
	self.e1.insert(0, '1')
	self.e1.grid(row=12, column=1, sticky=W)

        Label(master, text='with water  &lt; ').grid(row=13, sticky=W)
	self.e2 = Entry(master, width=5)
	self.e2.insert(0, '0')
	self.e2.grid(row=13, column=1, sticky=W)

        Label(master, text='total  &lt; ').grid(row=14, sticky=W)
	self.e3 = Entry(master, width=5)
	self.e3.insert(0, '2')
	self.e3.grid(row=14, column=1, sticky=W)

        return self.e1 # initial focus

    def validate(self):
 	try:
            self.num_hbonds_to_protein= int(self.e1.get())
            self.num_hbonds_to_water  = int(self.e2.get())
            self.num_hbonds_total     = int(self.e3.get())
            return 1

	except ValueError:
            tkMessageBox.showwarning(
			'Bad input',
			'Illegal values, please try again'
            )
            return 0

    def apply(self):
        self.num_hbonds_to_protein= int(self.e1.get())
        self.num_hbonds_to_water  = int(self.e2.get())
        self.num_hbonds_total     = int(self.e3.get())

        self.ok_flag = 1

    def cancel(self, event=None):
        # put focus back to the parent window
        self.parent.focus_set()
        self.destroy()
        


#######################################################################################
class saveDialog(tkSimpleDialog.Dialog):
	def body(self, master):
		global base_dir

		self.ok_flag = 0
		self.project_dir = ''

		Label(master, text='Base directory ').grid(row=0, column=0, sticky=W)
		Label(master, text='Project subdirectory ').grid(row=1, column=0, sticky=W)

		curdir = os.getcwd()
		self.e1 = Entry(master, width=50)
		self.e1.insert(0, curdir)
		self.e1.grid(row=0, column=1)
		self.e3 = Button(master, text='Browse', command=self.read_base_dir)
		self.e3.grid(row=0, column=2)

		self.e2 = Entry(master, width=50)
		self.e2.insert(0, 'project_name')
		self.e2.grid(row=1, column=1)


		return self.e1 # initial focus

	def validate(self):
 		try:
#			self.resname= self.e1.get()
			return 1

		except ValueError:
			tkMessageBox.showwarning(
				'Bad input',
				'Illegal values, please try again'
			)
			return 0

	def apply(self):
#		tmpdir = []
#		tmpdir.append(self.e1)
#		tmpdir.append(self.e2)
		self.project_dir = ''
		self.project_dir_short = ''
		self.project_dir = '%s/%s' % (self.e1.get(), self.e2.get())
                self.project_dir_short = '%s' % (self.e2.get())

		self.ok_flag = 1
#		print self.project_dir
#		cmd.alter(self.sel1,'resn=self.resname')

	def cancel(self, event=None):
# put focus back to the parent window
		self.parent.focus_set()
		self.destroy()

	def read_base_dir(self):
		base_dir = ''
		base_dir = askdirectory(title='select base directory', mustexist=1)
		self.e1.delete(0, END)
		self.e1.insert(0, base_dir)

#######################################################################################
class minimLig_dialog(tkSimpleDialog.Dialog):
    def body(self, master):
        self.ok_flag = 0
        self.object_name_lig = ''
        self.object_name_prot = ''

        Label(master, text='Select protein and possible ligand for molecular mechanics', font=('Helvetica', '14')).grid(row=0, columnspan=2, sticky=N)
        Label(master, text='  ').grid(row=1, columnspan=2, sticky=N)
        Label(master, text='Protein', relief='sunken', width=25, pady=4).grid(row=2, column=0, sticky=N)
        Label(master, text='Ligand', relief='sunken', width=25, pady=4).grid(row=2, column=1, sticky=N)

        
        self.rb_top0 = [[] for i in range(10000)]
        self.rb_top1 = [[] for i in range(10000)]
        # top level radio box to select between ligand only, ligand + protein(fixed), ligand + protein(zone), all
        self.v0 = StringVar()
        self.v1 = StringVar()
        ci = 0
        for na in cmd.get_names('objects'):
            try:
                cmd.select('pro', na)
                cmd.select('pro2', 'pro and resn %s' % PDBcode_protein)
                L = cmd.count_atoms('pro2')
                if L &gt; 0:
                    self.rb_top0[ci] = Radiobutton(master, text=na, variable=self.v0, value=na)
                    self.rb_top0[ci].grid(row=ci+3, column=0, sticky=W)
                    ci += 1
                cmd.delete('pro2')
                cmd.delete('pro')
            except:
                pass
            
        ci = 0
        for na in cmd.get_names('objects'):
            try:
                cmd.select('pro', na)
                cmd.select('pro2', 'pro and resn %s' % PDBcode_protein)
                L = cmd.count_atoms('pro2')
                if L == 0:
                    self.rb_top1[ci] = Radiobutton(master, text=na, variable=self.v1, value=na)
                    self.rb_top1[ci].grid(row=ci+3, column=1, sticky=W)
                    ci += 1
                cmd.delete('pro2')
                cmd.delete('pro')
            except:
                pass

        try:
            self.rb_top0[0].select()
        except:
            tkMessageBox.showwarning(
                'Attention',
                'Protein is missing.'
            )
            return 0
            
        try:
            self.rb_top1[0].select()
        except:
            tkMessageBox.showwarning(
                'Attention',
                'Ligand is missing. Please, separate ligand into separate object.'
            )
            return 0
#        self.v0.set(0)
        
    def validate(self):
        try:
            self.object_name_prot = self.v0.get()
            self.object_name_lig  = self.v1.get()
            return 1

        except ValueError:
            tkMessageBox.showwarning(
                'Attention',
                'Protein or ligand is missing. Please, separate ligand into separate object.'
            )
            return 0

    def apply(self):
        self.object_name_prot = self.v0.get()
        self.object_name_lig  = self.v1.get()
        self.ok_flag = 1

    def cancel(self, event=None):
        # put focus back to the parent window
        self.parent.focus_set()
        self.destroy()


#######################################################################################
class minimProt_dialog(tkSimpleDialog.Dialog):
    def body(self, master):
        self.ok_flag = 0

        Label(master, text='Select protein', font=('Helvetica', '14')).grid(row=0, columnspan=1, sticky=N)
        Label(master, text='  ').grid(row=1, columnspan=2, sticky=N)
        Label(master, text='Protein', relief='sunken', width=25, pady=4).grid(row=2, column=0, sticky=N)

        
        self.rb_top0 = [[] for i in range(10000)]
        # top level radio box to select between ligand only, ligand + protein(fixed), ligand + protein(zone), all
        self.v0 = StringVar()
        ci = 0
        for na in cmd.get_names('objects'):
            try:
                cmd.select('pro', na)
                cmd.select('pro2', 'pro and resn %s' % PDBcode_protein)
                L = cmd.count_atoms('pro2')
                if L &gt; 0:
                    self.rb_top0[ci] = Radiobutton(master, text=na, variable=self.v0, value=na)
                    self.rb_top0[ci].grid(row=ci+3, column=0, sticky=W)
                    ci += 1
                cmd.delete('pro2')
                cmd.delete('pro')
            except:
                pass
            

        try:
            self.rb_top0[0].select()
        except:
            tkMessageBox.showwarning(
                'Attention',
                'Protein is missing.'
            )
            
#        self.v0.set(0)
        
    def validate(self):
        try:
            self.object_name_prot = self.v0.get()
            return 1

        except ValueError:
            tkMessageBox.showwarning(
                'Attention',
                'Protein or ligand is missing. Please, separate ligand into separate object.'
            )
            return 0

    def apply(self):
        self.object_name_prot = self.v0.get()
        self.ok_flag = 1

    def cancel(self, event=None):
        # put focus back to the parent window
        self.parent.focus_set()
        self.destroy()



#######################################################################################
class minimizationDialog:
    def __init__(self, top):

        self.dialog = Pmw.Dialog(top,
                                 buttons = ('OK','Cancel'),
                                 defaultbutton = 'OK',
                                 title = 'Amber Plugin',
                                 command = self.apply)
                                 
        master = self.dialog.interior()

        Tkinter.Label(master, text='Specify settings for minimization').pack(fill='both',expand=1,padx=5,pady=5)
        
        nb1 = Pmw.NoteBook(master)

        # restraints page
        restraints_page = nb1.add('Restraints')
        
        self.v0 = Tkinter.StringVar()
        self.rb_top1 = Tkinter.Radiobutton(restraints_page, text='Ligand flexible, protein removed from interactions', variable=self.v0, value='lig')
        self.rb_top1.grid(row=0, column=0, sticky=W)
        self.rb_top2 = Tkinter.Radiobutton(restraints_page, text='Ligand flexible, protein restraint', variable=self.v0, value='lig_p_fixed')
        self.rb_top2.grid(row=1, column=0, sticky=W)
        self.rb_top3 = Tkinter.Radiobutton(restraints_page, text='Ligand flexible, protein restraint outside zone', variable=self.v0, value='lig_p_zone')
        self.rb_top3.grid(row=2, column=0, sticky=W)
        self.rb_top4 = Tkinter.Radiobutton(restraints_page, text='Ligand flexible, protein flexible', variable=self.v0, value='all')
        self.rb_top4.grid(row=3, column=0, sticky=W)

	self.v0.set('all')

	Tkinter.Label(restraints_page, text='Zone radius').grid(row=2, column=1, sticky=E)
	self.e1 = Tkinter.Entry(restraints_page, width=5)
	self.e1.insert(0, '8.0')
	self.e1.grid(row=2, column=2, sticky=W)                

        # ligand page
        ligand_page = nb1.add('Ligand')
        
        Tkinter.Label(ligand_page, text='Net charge of ligand ').grid(row=0, column=0, sticky=W)
	self.e2 = Tkinter.Entry(ligand_page, width=5)
	self.e2.insert(0, '0')
	self.e2.grid(row=0, column=1, sticky=W)

	Tkinter.Label(ligand_page, text='Charge calculation method:').grid(row=1, column=0, sticky=W)
	self.v1 = Tkinter.StringVar()
	self.rb1 = Tkinter.Radiobutton(ligand_page, text='Gasteiger', variable=self.v1, value='gas')
	self.rb1.grid(row=1, column=1, sticky=W)
	self.rb2 = Tkinter.Radiobutton(ligand_page, text='AM1-BCC', variable=self.v1, value='bcc')
	self.rb2.grid(row=2, column=1, sticky=W)
	self.v1.set('gas')

        # length page
        time_page = nb1.add('Time')

	Tkinter.Label(time_page, text='Number of minimization steps ').grid(row=0, column=0, sticky=W)
	self.e3 = Tkinter.Entry(time_page, width=5)
	self.e3.insert(0, '100')
	self.e3.grid(row=0, column=1, sticky=W)

        # solvation page
        solvation_page = nb1.add('Solvation')

	Tkinter.Label(solvation_page, text='Solvation method:').grid(row=0, column=0, sticky=W)
	self.v2 = Tkinter.StringVar()
	self.rb1a = Tkinter.Radiobutton(solvation_page, text='implicit (OBC)', variable=self.v2, value='obc')
	self.rb1a.grid(row=0, column=1, sticky=W)
	self.rb2a = Tkinter.Radiobutton(solvation_page, text='distance-dependent dielectric', variable=self.v2, value='ddd')
	self.rb2a.grid(row=1, column=1, sticky=W)
	self.v2.set('obc')



        # output page
        output_page = nb1.add('Energy')

        Tkinter.Label(output_page, text='Options for protein-ligand interaction energy output', width=70, pady=4).grid(row=0, columnspan=2, sticky=N)
	self.v_sie_yes = Tkinter.IntVar()
	self.cb_sie_yes = Tkinter.Checkbutton(output_page, text='Estimate free energy of binding using SIE', variable=self.v_sie_yes)
	self.cb_sie_yes.grid(row=1, column=0, sticky=W, padx=5)
	self.v_sie_yes.set(0)
	self.v_enout_yes = Tkinter.IntVar()
	self.cb_enout_yes = Tkinter.Checkbutton(output_page, text='Output potential energy', variable=self.v_enout_yes)
	self.cb_enout_yes.grid(row=2, column=0, sticky=W, padx=5)
	self.v_enout_yes.set(0)
	self.v_incsolv_yes = Tkinter.IntVar()
	self.cb_incsolv_yes = Tkinter.Checkbutton(output_page, text='Include solvation effects (PB/SA)', variable=self.v_incsolv_yes)
	self.cb_incsolv_yes.grid(row=2, column=1, sticky=W, padx=5)
	self.v_incsolv_yes.set(0)
        

        nb1.pack(fill='both',expand=1,padx=5,pady=5)
        nb1.setnaturalsize()

        self.dialog.activate(geometry = 'centerscreenalways')

    def apply(self, result):
        if result == 'OK':
            self.zone_radius = float(self.e1.get())
            self.net_charge = int(self.e2.get())
            self.min_steps = int(self.e3.get())
            self.bcc = self.v1.get()
            self.solvation = self.v2.get()
            self.mintype = self.v0.get()
            self.ok_flag = 1
            self.dialog.deactivate()
            self.dialog.withdraw()
        else:
            self.ok_flag = 0
            self.dialog.deactivate()
            self.dialog.withdraw()

#######################################################################################
class prepareProtein_dialog(tkSimpleDialog.Dialog):
    def body(self, master):
        self.ok_flag = 0

        Label(master, text='Select protein for preparation', font=('Helvetica', '14')).grid(row=0, columnspan=2, sticky=N)
        Label(master, text='  ').grid(row=1, columnspan=2, sticky=N)

        self.rb_top0 = [[] for i in range(10000)]
        # top level radio box to select between ligand only, ligand + protein(fixed), ligand + protein(zone), all
        self.v0 = StringVar()
        ci = 0
        for na in cmd.get_names('objects'):
            try:
                cmd.select('pro', na)
                cmd.select('pro2', 'pro and resn %s' % PDBcode_protein)
                L = cmd.count_atoms('pro2')
                if L &gt; 0:
                    self.rb_top0[ci] = Radiobutton(master, text=na, variable=self.v0, value=na)
                    self.rb_top0[ci].grid(row=ci+2, column=0, sticky=W)
                    ci += 1
                cmd.delete('pro2')
                cmd.delete('pro')
            except:
                pass
            

        self.rb_top0[0].select()
#        self.v0.set(0)
        
    def validate(self):
        try:
            return 1

        except ValueError:
            tkMessageBox.showwarning(
                'Bad input',
                'Illegal values, please try again'
            )
            return 0

    def apply(self):
        self.object_name = self.v0.get()
        self.ok_flag = 1

    def cancel(self, event=None):
        # put focus back to the parent window
        self.parent.focus_set()
        self.destroy()

#######################################################################################
class selectObject_dialog(tkSimpleDialog.Dialog):
    def body(self, master):
        self.ok_flag = 0

        Label(master, text='Select ligand for writing to mol2 file', font=('Helvetica', '14')).grid(row=0, columnspan=2, sticky=N)
        Label(master, text='  ').grid(row=1, columnspan=2, sticky=N)

        self.rb_top0 = [[] for i in range(10000)]
        # top level radio box to select between ligand only, ligand + protein(fixed), ligand + protein(zone), all
        self.v0 = StringVar()
        ci = 0
        for na in cmd.get_names('objects'):
            try:
                cmd.select('pro', na)
                cmd.select('pro2', 'pro and resn %s' % PDBcode_cofactors)
                L = cmd.count_atoms('pro2')
                if L == 0:
                    self.rb_top0[ci] = Radiobutton(master, text=na, variable=self.v0, value=na)
                    self.rb_top0[ci].grid(row=ci+2, column=0, sticky=W)
                    ci += 1
                cmd.delete('pro2')
                cmd.delete('pro')
            except:
                pass
            

        self.rb_top0[0].select()
#        self.v0.set(0)
        
    def validate(self):
        try:
            return 1

        except ValueError:
            tkMessageBox.showwarning(
                'Bad input',
                'Illegal values, please try again'
            )
            return 0

    def apply(self):
        self.object_name = self.v0.get()
        self.ok_flag = 1

    def cancel(self, event=None):
        # put focus back to the parent window
        self.parent.focus_set()
        self.destroy()


#######################################################################################
class monitor_dialog(tkSimpleDialog.Dialog):
    def body(self, master):

        self.ok_flag = 0

        Label(master, text='The following parts of the simulation have been finished. Please select parts for importing.', font=('Helvetica', '14')).grid(row=0, columnspan=3, sticky=N)

        self.rb_min = [[] for i in range(3)]
        self.rb_pr = [[] for i in range(2)]
        self.rb_equ = [[] for i in range(2)]
        self.rb_md = [[] for i in range(2)]
        self.min_done = 0
        self.pr_done = 0
        self.equ_done = 0
        self.md_done = 0

        # top level radio box
        ci = 0
        for na in monitor_list:
            if na == 'min.done':
                self.min_done = 1
		self.v_min = StringVar()
		Label(master, text='Minimization done').grid(row=ci+2, column=0,sticky=W)
                self.rb_min[0] = Radiobutton(master, text='Visual inspection', variable=self.v_min, value='visual')
                self.rb_min[0].grid(row=ci+2, column=1, sticky=W)
                self.rb_min[0].select()
                self.rb_min[1] = Radiobutton(master, text='Transfer data to client only', variable=self.v_min, value='import')
                self.rb_min[1].grid(row=ci+2, column=2, sticky=W)
                self.rb_min[0].select()
        if self.min_done == 0:
            Label(master, text='Minimization not yet finished.').grid(row=ci+2, column=0,sticky=W)
        ci+=1
        for na in monitor_list:
            if na == 'pr.done':
                self.pr_done = 1
		self.v_pr = StringVar()
		Label(master, text='Position restraint done').grid(row=ci+2, column=0,sticky=W)
                self.rb_pr[0] = Radiobutton(master, text='Visual inspection', variable=self.v_pr, value='visual')
                self.rb_pr[0].grid(row=ci+2, column=1, sticky=W)
                self.rb_pr[0].select()
                self.rb_pr[1] = Radiobutton(master, text='Transfer data to client only', variable=self.v_pr, value='import')
                self.rb_pr[1].grid(row=ci+2, column=2, sticky=W)
                self.rb_pr[0].select()
        if self.pr_done == 0:
            Label(master, text='Position restraint not yet finished.').grid(row=ci+2, column=0,sticky=W)
        ci+=1
        for na in monitor_list:
            if na == 'equ.done':
                self.equ_done = 1
		self.v_equ = StringVar()
		Label(master, text='Equilibration done').grid(row=ci+2, column=0,sticky=W)
                self.rb_equ[0] = Radiobutton(master, text='Visual inspection', variable=self.v_equ, value='visual')
                self.rb_equ[0].grid(row=ci+2, column=1, sticky=W)
                self.rb_equ[0].select()
                self.rb_equ[1] = Radiobutton(master, text='Transfer data to client only', variable=self.v_equ, value='import')
                self.rb_equ[1].grid(row=ci+2, column=2, sticky=W)
                self.rb_equ[0].select()
        if self.equ_done == 0:
            Label(master, text='Equilibration not yet finished.').grid(row=ci+2, column=0,sticky=W)
        ci+=1
        for na in monitor_list:
            if na == 'md.done':
                self.md_done = 1
		self.v_md = StringVar()
		Label(master, text='Production done').grid(row=ci+2, column=0,sticky=W)
                self.rb_md[0] = Radiobutton(master, text='Visual inspection', variable=self.v_md, value='visual')
                self.rb_md[0].grid(row=ci+2, column=1, sticky=W)
                self.rb_md[0].select()
                self.rb_md[1] = Radiobutton(master, text='Transfer data to client only', variable=self.v_md, value='import')
                self.rb_md[1].grid(row=ci+2, column=2, sticky=W)
                self.rb_md[0].select()
        if self.md_done == 0:
            Label(master, text='Production not yet finished.').grid(row=ci+2, column=0,sticky=W)
        ci+=1
        
    def validate(self):
        try:
            return 1

        except ValueError:
            tkMessageBox.showwarning(
                'Bad input',
                'Illegal values, please try again'
            )
            return 0

    def apply(self):
        if self.min_done == 1:
            self.min_whattodo = self.v_min.get()
        if self.pr_done == 1:
            self.pr_whattodo = self.v_pr.get()
        if self.equ_done == 1:
            self.equ_whattodo = self.v_equ.get()
        if self.md_done == 1:
            self.md_whattodo = self.v_md.get()
        self.ok_flag = 1

    def cancel(self, event=None):
        # put focus back to the parent window
        self.parent.focus_set()
        self.destroy()

#######################################################################################
class sie_dialog(tkSimpleDialog.Dialog):
    def body(self, master):

        self.ok_flag = 0

        Label(master, text='Please specify settings for SIE calculation.', font=('Helvetica', '14')).grid(row=0, columnspan=3, sticky=N)

        fi = open('md.in', 'r')

        for line in fi:
            if line.find('nstlim') &gt; -1:
                aa1, aa2 = line.split(', ', 1)
                i = aa1.find('=') + 1
                num_steps = int(aa1[i:])
            if line.find('ntwx') &gt; -1:
                aa1, aa2, aa3 = line.split(', ', 2)
                i = aa2.find('=') + 1
                num_frq_out = int(aa2[i:])
        self.max_frames = num_steps/num_frq_out;

        Label(master, text='First frame (1 - last frame)').grid(row=2, column=0, sticky=W)
	self.e2a = Entry(master, width=5)
	self.e2a.insert(0, '1')
	self.e2a.grid(row=2, column=1)

        Label(master, text='Last frame (first frame - %d)' % (self.max_frames)).grid(row=3, column=0, sticky=W)
	self.e2b = Entry(master, width=5)
	self.e2b.insert(0, self.max_frames)
	self.e2b.grid(row=3, column=1)

        Label(master, text='Interval').grid(row=4, column=0, sticky=W)
	self.e2c = Entry(master, width=5)
	self.e2c.insert(0, '1')
	self.e2c.grid(row=4, column=1)
        
       
    def validate(self):
        try:
            self.start_frame = int(self.e2a.get())
            self.end_frame = int(self.e2b.get())
            self.interval = int(self.e2c.get())
            if self.start_frame &gt; 0 and self.start_frame &lt; self.end_frame and self.end_frame &lt;= self.max_frames:
                return 1
            else:
                tkMessageBox.showwarning(
                    'Bad input',
                    'Illegal values, please try again'
                )

        except ValueError:
            tkMessageBox.showwarning(
                'Bad input',
                'Illegal values, please try again'
            )
            return 0

    def apply(self):
        self.start_frame = int(self.e2a.get())
        self.end_frame = int(self.e2b.get())
        self.interval = int(self.e2c.get())
        self.ok_flag = 1

    def cancel(self, event=None):
        # put focus back to the parent window
        self.parent.focus_set()
        self.destroy()

#######################################################################################
class mmpbsa_format_dialog(tkSimpleDialog.Dialog):
    def body(self, master):
	
        self.ok_flag = 0

        Label(master, text='Please specify source of input for MM/PBSA calculation.', font=('Helvetica', '14')).grid(row=0, columnspan=3, sticky=N)

	self.v2 = StringVar()
	self.rb1a = Radiobutton(master, text='From GROMACS using AMBER force field (gro + NMR-pdb file)', variable=self.v2, value='gro')
	self.rb1a.grid(row=42, column=1, sticky=W)
	self.rb2a = Radiobutton(master, text='From AMBER (pdb + trj/crd file)', variable=self.v2, value='amb')
	self.rb2a.grid(row=43, column=1, sticky=W)

	self.rb1a.select()
	self.v2.set('amb')
        
       
    def validate(self):
        try:
            self.mmpbsa_source = self.v2.get()
            return 1

        except ValueError:
            tkMessageBox.showwarning(
                'Bad input',
                'Illegal values, please try again'
            )
            return 0

    def apply(self):
        self.mmpbsa_source = self.v2.get()
        self.ok_flag = 1

    def cancel(self, event=None):
        # put focus back to the parent window
        self.parent.focus_set()
        self.destroy()

#######################################################################################
class mmpbsa_source_dialog(tkSimpleDialog.Dialog):
    def __init__(self, master, title = None, flag_source = 'gro'):
        self.flag_source = flag_source
        Toplevel.__init__(self, master)
        self.transient(master)
        if title:
            self.title(title)
        self.parent = master
        self.result = None
        body = Frame(self)
        self.initial_focus = self.body(body)
        body.pack(padx=5, pady=5)
        self.buttonbox()
        self.grab_set()
        if not self.initial_focus:
            self.initial_focus = self
        self.protocol('WM_DELETE_WINDOW', self.cancel)
        self.geometry('+%d+%d' % (master.winfo_rootx()+50, master.winfo_rooty()+50))
        self.initial_focus.focus_set()
#        self.grab_release()
        self.wait_window(self)	
        
    def body(self, master):

        self.ok_flag = 0
				
	curdir = os.getcwd()

        Label(master, text='Please specify input files and output directory for MM/PBSA calculation.', font=('Helvetica', '14')).grid(row=0, columnspan=3, sticky=N)
#        print self.flag_source

        if self.flag_source == 'gro':
            Label(master, text='gro file: ').grid(row=1, column=0, sticky=W, padx=5)
            self.e_top = Entry(master, width=125)
#            self.e_top.insert(0, '.gro')
#            self.e_top.insert(0, '/home/shared/MLDaniel/MMPBSA/7_16/prot_md.gro')
            self.e_top.insert(0, '/mnt/lar/home/mlill/Desktop/Simulations/cyp2c9/MMPBSA_8_8_09/prot_md0.gro')
#            self.e_top.insert(0, '/mnt/lar/home/mlill/Desktop/Simulations/cyp2c9/MMPBSA/prot_equ0.gro')
            self.e_top.grid(row=1, column=1, sticky=W, padx=5)
            self.b_top = Button(master, text='Select gro file', command=self.read_gro_file)
            self.b_top.grid(row=1, column=2, sticky=W, padx=5)
        
            Label(master, text='NMR-pdb file: ').grid(row=2, column=0, sticky=W, padx=5)
            self.e_trj = Entry(master, width=125)
#            self.e_trj.insert(0, '.pdb')
#            self.e_trj.insert(0, '/home/shared/MLDaniel/MMPBSA/7_16/prot_md_NMR.pdb')
            self.e_trj.insert(0, '/mnt/lar/home/mlill/Desktop/Simulations/cyp2c9/MMPBSA_8_8_09/prot_md_NMR.pdb')
#            self.e_trj.insert(0, '/mnt/lar/home/mlill/Desktop/Simulations/cyp2c9/MMPBSA/prot_equ_NMR.pdb')
            self.e_trj.grid(row=2, column=1, sticky=W, padx=5)
            self.b_trj = Button(master, text='Select pdb file', command=self.read_nmr_file)
            self.b_trj.grid(row=2, column=2, sticky=W, padx=5)

            Label(master, text='Output directory on server: ').grid(row=3, column=0, sticky=W, padx=5)
            self.e_out = Entry(master, width=125)
            self.e_out.insert(0, 'tmp_mmpbsa_0')
            self.e_out.grid(row=3, column=1, sticky=W, padx=5)
            Label(master, text='(will be generated/overwritten').grid(row=3, column=2, sticky=W, padx=5)
        else:

            Label(master, text='pdb file: ').grid(row=1, column=0, sticky=W, padx=5)
            self.e_top = Entry(master, width=125)
            self.e_top.insert(0, '%s/equ_fin.pdb' % curdir)
#            self.e_top.insert(0, '/mnt/lar/home/mlill/Desktop/Simulations/Simulations_MMPBSA/1MU6_cmp1_client/min_fin.pdb')
            self.e_top.grid(row=1, column=1, sticky=W, padx=5)
            self.b_top = Button(master, text='Select pdb file', command=self.read_pdb_file)
            self.b_top.grid(row=1, column=2, sticky=W, padx=5)
        
            Label(master, text='trj/crd file: ').grid(row=2, column=0, sticky=W, padx=5)
            self.e_trj = Entry(master, width=125)
            self.e_trj.insert(0, '%s/md.trj' % curdir)
#            self.e_trj.insert(0, '/mnt/lar/home/mlill/Desktop/Simulations/Simulations_MMPBSA/1MU6_cmp1_client/md_short.trj')
            self.e_trj.grid(row=2, column=1, sticky=W, padx=5)
            self.b_trj = Button(master, text='Select trj/crd file', command=self.read_trj_file)
            self.b_trj.grid(row=2, column=2, sticky=W, padx=5)
        
            Label(master, text='in file for generation of trj/crd file: ').grid(row=3, column=0, sticky=W, padx=5)
            self.e_in = Entry(master, width=125)
            self.e_in.insert(0, '%s/md.in' % curdir)
#            self.e_trj.insert(0, '/mnt/lar/home/mlill/Desktop/Simulations/Simulations_MMPBSA/1MU6_cmp1_client/md_short.trj')
            self.e_in.grid(row=3, column=1, sticky=W, padx=5)
            self.b_in = Button(master, text='Select in file', command=self.read_in_file)
            self.b_in.grid(row=3, column=2, sticky=W, padx=5)

            Label(master, text='Output directory on server: ').grid(row=4, column=0, sticky=W, padx=5)
            self.e_out = Entry(master, width=125)
            self.e_out.insert(0, 'tmp_mmpbsa_0')
            self.e_out.grid(row=4, column=1, sticky=W, padx=5)
            Label(master, text='(will be generated/overwritten').grid(row=4, column=2, sticky=W, padx=5)
       
    def read_gro_file(self):
	ftypes=(('gro file', '*.gro'), ('All files', '*'))
	indir = os.getcwd()
	openfile = askopenfilename(initialdir=indir, filetypes=ftypes)
	if openfile:
#		self.top_filename = os.path.basename(openfile)
		self.e_top.delete(0, END)
#		self.e_top.insert(0, self.top_filename)
		self.e_top.insert(0, openfile)

    def read_nmr_file(self):
	ftypes=(('pdb file', '*.pdb'), ('All files', '*'))
	indir = os.getcwd()
	openfile = askopenfilename(initialdir=indir, filetypes=ftypes)
	if openfile:
#		self.trj_filename = os.path.basename(openfile)
		self.e_trj.delete(0, END)
#		self.e_trj.insert(0, self.trj_filename)
		self.e_trj.insert(0, openfile)

    def read_pdb_file(self):
	ftypes=(('pdb file', '*.pdb'), ('All files', '*'))
	indir = os.getcwd()
	openfile = askopenfilename(initialdir=indir, filetypes=ftypes)
	if openfile:
#		self.top_filename = os.path.basename(openfile)
		self.e_top.delete(0, END)
#		self.e_top.insert(0, self.top_filename)
		self.e_top.insert(0, openfile)

    def read_trj_file(self):
	ftypes=(('trj file', '*.trj'), ('crd file', '*.crd'), ('All files', '*'))
	indir = os.getcwd()
	openfile = askopenfilename(initialdir=indir, filetypes=ftypes)
	if openfile:
#		self.trj_filename = os.path.basename(openfile)
		self.e_trj.delete(0, END)
#		self.e_trj.insert(0, self.trj_filename)
		self.e_trj.insert(0, openfile)
    
    def read_in_file(self):
	ftypes=(('in file', '*.in'), ('All files', '*'))
	indir = os.getcwd()
	openfile = askopenfilename(initialdir=indir, filetypes=ftypes)
	if openfile:
#		self.trj_filename = os.path.basename(openfile)
		self.e_in.delete(0, END)
#		self.e_trj.insert(0, self.trj_filename)
		self.e_in.insert(0, openfile)
    
    def validate(self):
        try:
            return 1

        except ValueError:
            tkMessageBox.showwarning(
                'Bad input',
                'Illegal values, please try again'
            )
            return 0

    def apply(self):
        self.file_top = self.e_top.get()
        self.file_trj = self.e_trj.get()
        self.file_in = self.e_in.get()
        self.dir_out = self.e_out.get()
        self.ok_flag = 1

    def cancel(self, event=None):
        # put focus back to the parent window
        self.parent.focus_set()
        self.destroy()

#######################################################################################
class mmpbsa_ligands_dialog(tkSimpleDialog.Dialog):
    def body(self, master):

        self.ok_flag = 0

        Label(master, text='Please specify how to handle non-standard residues.', font=('Helvetica', '14')).grid(row=0, columnspan=4, sticky=N)
        Label(master, text='... as ligand.', font=('Helvetica', '12')).grid(row=1, column=1, sticky=N)
        Label(master, text='... as protein.', font=('Helvetica', '12')).grid(row=1, column=2, sticky=N)
        Label(master, text='remove completely.', font=('Helvetica', '12')).grid(row=1, column=3, sticky=N)

        self.rb_top0 = [[] for i in range(1000)]
        self.rb_top1 = [[] for i in range(1000)]
        self.rb_top2 = [[] for i in range(1000)]
        self.v0 = [[] for i in range(1000)]
        self.handle_ligand = [[] for i in range(1000)]
        # top level radio box to select between ligand only, ligand + protein(fixed), ligand + protein(zone), all
        ci = 0
        for na in non_prot_res_list:
            try:
                self.v0[ci] = StringVar()
                Label(master, text=na, font=('Helvetica', '12')).grid(row=ci+10, column=0, sticky=N)
                self.rb_top0[ci] = Radiobutton(master, text='', variable=self.v0[ci], value='lig')
                self.rb_top0[ci].grid(row=ci+10, column=1, sticky=N)
                self.rb_top1[ci] = Radiobutton(master, text='', variable=self.v0[ci], value='prot')
                self.rb_top1[ci].grid(row=ci+10, column=2, sticky=N)
                self.rb_top2[ci] = Radiobutton(master, text='', variable=self.v0[ci], value='remove')
                self.rb_top2[ci].grid(row=ci+10, column=3, sticky=N)
                self.v0[ci].set('prot')
                ci += 1
            except:
                pass
            

        self.rb_top1[0].select()
#        self.v0.set(0)
        
    def validate(self):
        try:
            ci = 0
            for na in non_prot_res_list:
                self.handle_ligand[ci] = self.v0[ci].get()
                ci += 1
            return 1

        except ValueError:
            tkMessageBox.showwarning(
                'Bad input',
                'Illegal values, please try again'
            )
            return 0

    def apply(self):
        self.ok_flag = 1
        ci = 0
        for na in non_prot_res_list:
            self.handle_ligand[ci] = self.v0[ci].get()
            ci += 1

    def cancel(self, event=None):
        # put focus back to the parent window
        self.parent.focus_set()
        self.destroy()

#######################################################################################
#######################################################################################
class mmpbsa_frames_dialog:
	def __init__(self, top, input_file):
		self.dialog = Pmw.Dialog(top,
					buttons = ('Ok','Cancel'),
					defaultbutton = 'Ok',
					title = 'Please specify settings for MMPBSA calculation.',
					command = self.apply)

		self.curdir = os.getcwd()
 	                                
		master = self.dialog.interior()


		self.ok_flag = 0

		fi = open(input_file, 'r')

		for line in fi:
			if line.find('nstlim') &gt; -1:
				aa1, aa2 = line.split(', ', 1)
				i = aa1.find('=') + 1
				num_steps = int(aa1[i:])
			if line.find('ntwx') &gt; -1:
				aa1, aa2, aa3 = line.split(', ', 2)
				i = aa2.find('=') + 1
				num_frq_out = int(aa2[i:])
		self.max_frames = num_steps/num_frq_out;

		Label(master, text='First frame (1 - last frame)').grid(row=2, column=0, sticky=W)
		self.e2a = Entry(master, width=5)
		self.e2a.insert(0, '1')
		self.e2a.grid(row=2, column=1)

		Label(master, text='Last frame (first frame - %d)' % (self.max_frames)).grid(row=3, column=0, sticky=W)
		self.e2b = Entry(master, width=5)
		self.e2b.insert(0, self.max_frames)
		self.e2b.grid(row=3, column=1)

		Label(master, text='Interval (PBSA part)').grid(row=4, column=0, sticky=W)
		self.e2c = Entry(master, width=5)
		self.e2c.insert(0, '1')
		self.e2c.grid(row=4, column=1)
        
		Label(master, text='Interval (Entropy part)').grid(row=5, column=0, sticky=W)
		self.e2d = Entry(master, width=5)
		self.e2d.insert(0, '10')
		self.e2d.grid(row=5, column=1)

		self.dialog.activate(geometry = 'centerscreenalways')

	def apply(self, result):
		if result == 'Cancel':
			self.ok_flag = 0
			self.dialog.deactivate()
			self.dialog.withdraw()
		else:
			self.ok_flag = 1
			self.start_frame = int(self.e2a.get())
			self.end_frame = int(self.e2b.get())
			self.interval = int(self.e2c.get())
			self.interval_entropy = int(self.e2d.get())
			if self.start_frame &gt; 0 and self.start_frame &lt; self.end_frame and self.end_frame &lt;= self.max_frames:
				self.ok_flag = 1
			else:
				tkMessageBox.showwarning(
					'Bad input',
					'Illegal values, please try again'
				)
				self.ok_flag = 0
			self.dialog.deactivate()
			self.dialog.withdraw()

 


"""

class mmpbsa_frames_dialog(tkSimpleDialog.Dialog):


    def body(self, master):

        self.ok_flag = 0

        Label(master, text='Please specify settings for MMPBSA calculation.', font=('Helvetica', '14')).grid(row=0, columnspan=3, sticky=N)

        fi = open('md.in', 'r')

        for line in fi:
            if line.find('nstlim') &gt; -1:
                aa1, aa2 = line.split(', ', 1)
                i = aa1.find('=') + 1
                num_steps = int(aa1[i:])
            if line.find('ntwx') &gt; -1:
                aa1, aa2, aa3 = line.split(', ', 2)
                i = aa2.find('=') + 1
                num_frq_out = int(aa2[i:])
        self.max_frames = num_steps/num_frq_out;

        Label(master, text='First frame (1 - last frame)').grid(row=2, column=0, sticky=W)
	self.e2a = Entry(master, width=5)
	self.e2a.insert(0, '1')
	self.e2a.grid(row=2, column=1)

        Label(master, text='Last frame (first frame - %d)' % (self.max_frames)).grid(row=3, column=0, sticky=W)
	self.e2b = Entry(master, width=5)
	self.e2b.insert(0, self.max_frames)
	self.e2b.grid(row=3, column=1)

        Label(master, text='Interval (PBSA part)').grid(row=4, column=0, sticky=W)
	self.e2c = Entry(master, width=5)
	self.e2c.insert(0, '1')
	self.e2c.grid(row=4, column=1)
        
        Label(master, text='Interval (Entropy part)').grid(row=5, column=0, sticky=W)
	self.e2d = Entry(master, width=5)
	self.e2d.insert(0, '10')
	self.e2d.grid(row=5, column=1)
       
    def validate(self):
        try:
            self.start_frame = int(self.e2a.get())
            self.end_frame = int(self.e2b.get())
            self.interval = int(self.e2c.get())
            self.interval_entropy = int(self.e2d.get())
            if self.start_frame &gt; 0 and self.start_frame &lt; self.end_frame and self.end_frame &lt;= self.max_frames:
                return 1
            else:
                tkMessageBox.showwarning(
                    'Bad input',
                    'Illegal values, please try again'
                )

        except ValueError:
            tkMessageBox.showwarning(
                'Bad input',
                'Illegal values, please try again'
            )
            return 0

    def apply(self):
        self.start_frame = int(self.e2a.get())
        self.end_frame = int(self.e2b.get())
        self.interval = int(self.e2c.get())
        self.interval_entropy = int(self.e2d.get())
        self.ok_flag = 1

    def cancel(self, event=None):
        # put focus back to the parent window
        self.parent.focus_set()
        self.destroy()
"""

#######################################################################################
class reduceMessage:
        def __init__(self, parent):
                top = self.top = Toplevel(parent)
        
		self.ok_flag = 0

                Label(top, text='Detailed results from reduce', font=('Helvetica', '16')).grid(row=0, columnspan=3, sticky=N)
                Label(top, text='  ').grid(row=1, columnspan=6, sticky=N)
                

                red_file = open('Reduce.log', 'r')
                ci = 2
                for i in red_file:
                    j = i.rstrip()
                    Label(top, text='%s' % (j), font=('Helvetica', '12', 'bold')).grid(row=ci, column=0, sticky=W)
                    ci += 1
                
                red_file.close()

                
                b = Button(top, text='Close', padx=5, command=self.ok)        
                b.grid(row=1000, column=1, sticky=S)


        def ok(self):
                self.top.destroy()
                
#######################################################################################
class InfoMessage(Frame):
    def __init__(self, master=None, text=''):
        Frame.__init__(self, master)
        master.title('Progress information')
        self.text = text
        self.createText()
        self.pack()
        
    def createText(self):
        self.txt = Label(self, text=self.text, font=('Helvectica', '16'))
        self.txt.pack({'side': 'left'})


#######################################################################################
class sie_results(tkSimpleDialog.Dialog):
    def body(self, master):

        self.ok_flag = 0

        Label(master, text='SIE results:', font=('Courier', 10, 'bold')).grid(row=0, columnspan=1, sticky=N)

        sie_file = open('sie_ave.out', 'r')
        ci = 2
        for i in sie_file:
            j = i.rstrip()
            Label(master, text='%s' % (j), font=('Courier', 10, 'bold')).grid(row=ci, column=0, sticky=W)
            ci += 1
        
        sie_file.close()
       
    def validate(self):
        try:
            return 1

        except ValueError:
            tkMessageBox.showwarning(
                'Bad input',
                'Illegal values, please try again'
            )
            return 0

    def apply(self):
        self.ok_flag = 1

    def cancel(self, event=None):
        # put focus back to the parent window
        self.parent.focus_set()
        self.destroy()

#######################################################################################
class mmpbsa_results(tkSimpleDialog.Dialog):
    def body(self, master):

        self.ok_flag = 0

        Label(master, text='MM_PBSA results:', font=('Courier', 10, 'bold')).grid(row=0, columnspan=1, sticky=N)

        sie_file = open('snapshot_statistics.out', 'r')
        ci = 2
        for i in sie_file:
            j = i.rstrip()
            Label(master, text='%s' % (j), font=('Courier', 10, 'bold')).grid(row=ci, column=0, sticky=W)
            ci += 1
        
        sie_file.close()
       
    def validate(self):
        try:
            return 1

        except ValueError:
            tkMessageBox.showwarning(
                'Bad input',
                'Illegal values, please try again'
            )
            return 0

    def apply(self):
        self.ok_flag = 1

    def cancel(self, event=None):
        # put focus back to the parent window
        self.parent.focus_set()
        self.destroy()

#######################################################################################
def write_mol2(sel1, filename):

# save pdb and mol file
	cmd.save('%s.pdb' % (filename), sel1, 0, 'pdb')
	cmd.save('%s.mol' % (filename), sel1, 0, 'mol')
# translate mol into mol2 file
        os.system('babel -imol %s.mol -omol2 %s.mol2\n' % (filename, filename))
#        return 0
# change atom names in mol2 file to those in pdb file
	f_pdb = open('%s.pdb' % (filename), 'r')
	atnam = []
	resnam = []
	i = 0
	for line in f_pdb:
		if line[0:4] == 'ATOM' or line[0:6] == 'HETATM':
                    # Br atoms are written one column to the left by pymol
                    if line[12:13] == 'B':
                        atnam.append(line[12:15])
                    elif line[12:13] == 'C':
                        atnam.append(line[12:15])
                    else:
			atnam.append(line[13:16])
                    resnam.append(line[17:21])
                    i = i + 1
	f_pdb.close()
        

	f_old = open('%s.mol2' % (filename), 'r')
	f_new = open('new.mol2', 'w')
	flag = 0
	for line in f_old:
		if line[0:13] == '@&lt;TRIPOS&gt;BOND':
			flag = 0
		if flag == 0:
			f_new.write(line)
		else:
			new_line = []
			new_line.append(line[0:8])
			new_line.append(str(atnam.pop(0)))
			new_line.append(line[11:58])
			new_line.append(str(resnam.pop(0)))
			new_line.append(line[62:])
			f_new.write(''.join(new_line))
		if line[0:13] == '@&lt;TRIPOS&gt;ATOM':
			flag = 1

	f_old.close()
	f_new.close()

        os.remove('%s.mol2' % (filename))
        os.rename('new.mol2', '%s.mol2' % (filename))
        os.remove('%s.mol' % (filename))
        os.remove('%s.pdb' % (filename))



#######################################################################################
class mdsimulationDialog:
    def __init__(self, top):

        self.dialog = Pmw.Dialog(top,
                                 buttons = ('OK','Cancel'),
                                 defaultbutton = 'OK',
                                 title = 'Amber Plugin',
                                 command = self.apply)
                                 
        master = self.dialog.interior()

        Tkinter.Label(master, text='Specify settings for molecular dynamics simulation').pack(fill='both',expand=1,padx=5,pady=5)
        
        nb1 = Pmw.NoteBook(master)

        # restraints page
        restraints_page = nb1.add('Restraints')
        
        self.v0 = Tkinter.StringVar()
        self.rb_top1 = Tkinter.Radiobutton(restraints_page, text='Ligand flexible, protein removed from interactions', variable=self.v0, value='lig')
        self.rb_top1.grid(row=0, column=0, sticky=W)
        self.rb_top2 = Tkinter.Radiobutton(restraints_page, text='Ligand flexible, protein restraint', variable=self.v0, value='lig_p_fixed')
        self.rb_top2.grid(row=1, column=0, sticky=W)
        self.rb_top3 = Tkinter.Radiobutton(restraints_page, text='Ligand flexible, protein restraint outside zone', variable=self.v0, value='lig_p_zone')
        self.rb_top3.grid(row=2, column=0, sticky=W)
        self.rb_top4 = Tkinter.Radiobutton(restraints_page, text='Ligand flexible, protein flexible', variable=self.v0, value='all')
        self.rb_top4.grid(row=3, column=0, sticky=W)

	self.v0.set('all')

	Tkinter.Label(restraints_page, text='Zone radius').grid(row=2, column=1, sticky=E)
	self.e1 = Tkinter.Entry(restraints_page, width=5)
	self.e1.insert(0, '8.0')
	self.e1.grid(row=2, column=2, sticky=W)                

        # ligand page
        ligand_page = nb1.add('Ligand')
        
        Tkinter.Label(ligand_page, text='Net charge of ligand ').grid(row=0, column=0, sticky=W)
	self.e2 = Tkinter.Entry(ligand_page, width=5)
	self.e2.insert(0, '0')
	self.e2.grid(row=0, column=1, sticky=W)

	Tkinter.Label(ligand_page, text='Charge calculation method:').grid(row=1, column=0, sticky=W)
	self.v1 = Tkinter.StringVar()
	self.rb1 = Tkinter.Radiobutton(ligand_page, text='Gasteiger', variable=self.v1, value='gas')
	self.rb1.grid(row=1, column=1, sticky=W)
	self.rb2 = Tkinter.Radiobutton(ligand_page, text='AM1-BCC', variable=self.v1, value='bcc')
	self.rb2.grid(row=2, column=1, sticky=W)
	self.v1.set('bcc')


        # length page
        time_page = nb1.add('Time')

	self.v_min_yes = Tkinter.IntVar()
	self.cb_min_yes = Tkinter.Checkbutton(time_page, text='Minimization', variable=self.v_min_yes, state=DISABLED, disabledforeground='black')
	self.cb_min_yes.grid(row=0, column=0, sticky=W, padx=5)
	Tkinter.Label(time_page, text='Number of minimization steps ').grid(row=0, column=1,sticky=W)
	self.e_min = Tkinter.Entry(time_page, width=10)
	self.e_min.insert(0, '500')
	self.e_min.grid(row=0, column=2)
	self.v_min_yes.set(1)

	self.v_pr_yes = Tkinter.IntVar()
	self.cb_pr_yes = Tkinter.Checkbutton(time_page, text='Equilibration (water only)', variable=self.v_pr_yes, command = self.setcheckbutton)
	self.cb_pr_yes.grid(row=1, column=0, sticky=W, padx=5)
	Tkinter.Label(time_page, text='Number of MD steps ').grid(row=1, column=1,sticky=W)
	self.e_pr = Tkinter.Entry(time_page, width=10)
	self.e_pr.insert(0, '125000')
	self.e_pr.grid(row=1, column=2)
	Tkinter.Label(time_page, text='Time step (in fs) ').grid(row=1, column=3,sticky=W)
	self.e_pr_dt = Tkinter.Entry(time_page, width=5)
	self.e_pr_dt.insert(0, '2.0')
	self.e_pr_dt.grid(row=1, column=4)
	Tkinter.Label(time_page, text='Frequency for output ').grid(row=1, column=5,sticky=W)
	self.e_pr_fo = Tkinter.Entry(time_page, width=8)
	self.e_pr_fo.insert(0, '5000')
	self.e_pr_fo.grid(row=1, column=6)
	self.v_pr_yes.set(1)

	self.v_equ_yes = Tkinter.IntVar()
	self.cb_equ_yes = Tkinter.Checkbutton(time_page, text='Equilibration', variable=self.v_equ_yes, command = self.setcheckbutton)
	self.cb_equ_yes.grid(row=2, column=0, sticky=W, padx=5)
	Tkinter.Label(time_page, text='Number of MD steps ').grid(row=2, column=1,sticky=W)
	self.e_equ= Tkinter.Entry(time_page, width=10)
	self.e_equ.insert(0, '250000')
	self.e_equ.grid(row=2, column=2)
	Tkinter.Label(time_page, text='Time step (in fs) ').grid(row=2, column=3,sticky=W)
	self.e_equ_dt = Tkinter.Entry(time_page, width=5)
	self.e_equ_dt.insert(0, '2.0')
	self.e_equ_dt.grid(row=2, column=4)
	Tkinter.Label(time_page, text='Frequency for output ').grid(row=2, column=5,sticky=W)
	self.e_equ_fo = Tkinter.Entry(time_page, width=8)
	self.e_equ_fo.insert(0, '5000')
	self.e_equ_fo.grid(row=2, column=6)
	self.v_equ_yes.set(1)

	self.v_md_yes = Tkinter.IntVar()
	self.cb_md_yes = Tkinter.Checkbutton(time_page, text='Production', variable=self.v_md_yes, command = self.setcheckbutton)
	self.cb_md_yes.grid(row=3, column=0, sticky=W, padx=5)
	Tkinter.Label(time_page, text='Number of MD steps ').grid(row=3, column=1,sticky=W)
	self.e_md= Tkinter.Entry(time_page, width=10)
	self.e_md.insert(0, '500000')
	self.e_md.grid(row=3, column=2)
	Tkinter.Label(time_page, text='Time step (in fs) ').grid(row=3, column=3,sticky=W)
	self.e_md_dt = Tkinter.Entry(time_page, width=5)
	self.e_md_dt.insert(0, '2.0')
	self.e_md_dt.grid(row=3, column=4)
	Tkinter.Label(time_page, text='Frequency for output ').grid(row=3, column=5,sticky=W)
	self.e_md_fo = Tkinter.Entry(time_page, width=8)
	self.e_md_fo.insert(0, '5000')
	self.e_md_fo.grid(row=3, column=6)
	self.v_md_yes.set(1)


        # solvation page
        solvation_page = nb1.add('Solvation')

	Tkinter.Label(solvation_page, text='Solvation method:').grid(row=0, column=0, sticky=W,padx=5,pady=5)

	self.v2 = Tkinter.StringVar()
	self.rb_solv1 = Tkinter.Radiobutton(solvation_page, text='Implicit (OBC)', variable=self.v2, value='solv_implicit')
	self.rb_solv1.grid(row=1, column=0, sticky=W,padx=5,pady=5)
	self.rb_solv2 = Tkinter.Radiobutton(solvation_page, text='Solvation cap', variable=self.v2, value='solv_cap')
	self.rb_solv2.grid(row=2, column=0, sticky=W,padx=5,pady=5)
	self.rb_solv3 = Tkinter.Radiobutton(solvation_page, text='Solvation box', variable=self.v2, value='solv_box')
	self.rb_solv3.grid(row=3, column=0, sticky=W,padx=5,pady=5)
	self.rb_solv2.select()
	self.v2.set('solv_implicit')

	Tkinter.Label(solvation_page, text='Cap radius').grid(row=2, column=1, sticky=W,padx=5,pady=5)
	self.e2a = Tkinter.Entry(solvation_page, width=5)
	self.e2a.insert(0, '25.0')
	self.e2a.grid(row=2, column=2,padx=5,pady=5)

	Tkinter.Label(solvation_page, text='Distance to boundary').grid(row=3, column=1, sticky=W,padx=5,pady=5)
	self.e2b = Entry(solvation_page, width=5)
	self.e2b.insert(0, '10.0')
	self.e2b.grid(row=3, column=2,padx=5,pady=5)


        # resource page
        resource_page = nb1.add('Resource')

        group1 = Pmw.Group(resource_page, tag_text='Project definition name')
	self.v3 = Tkinter.StringVar()
	self.rs_top1 = Tkinter.Radiobutton(group1.interior(), text='Start job in the background', variable=self.v3, value='start')
	self.rs_top1.grid(row=0, column=0, sticky=W,padx=5,pady=5)
	self.rs_top2 = Tkinter.Radiobutton(group1.interior(), text='Just prepare files for background job', variable=self.v3, value='prep')
	self.rs_top2.grid(row=1, column=0, sticky=W,padx=5,pady=5)
	self.rs_top1.select()
	self.v3.set('start')
        group1.grid(row=0, column=0, sticky=W,padx=5,pady=5)

        group2 = Pmw.Group(resource_page, tag_text='Select computer/compute cluster')
        self.rc_top = [[] for i in range(100000)]
        self.ec_top = [[] for i in range(100000)]
        self.vc = Tkinter.StringVar()
        self.rc_top[0] = Tkinter.Radiobutton(group2.interior(), text='local', variable=self.vc, value='local', indicatoron='false', width=50)
        self.rc_top[0].grid(row=0, column=0, sticky=E,padx=5,pady=5)
        Tkinter.Label(group2.interior(), text='Number of processors/cores [max. %d]: ' % (int(os.sysconf('SC_NPROCESSORS_ONLN')))).grid(row=0, column=1, sticky=W,padx=5,pady=5)
        self.ec_top[0] = Tkinter.Entry(group2.interior(), width=5)
        self.ec_top[0].insert(0, '1')
        self.ec_top[0].grid(row=0, column=2,padx=5,pady=5)
        ci = 1
        for i in SERVER_nodename:
            if ci &lt;= SERVER_number_of:
            	na = str(i)
            	self.rc_top[ci] = Tkinter.Radiobutton(group2.interior(), text=na, variable=self.vc, value=na, indicatoron='false', width=50)
            	self.rc_top[ci].grid(row=ci, column=0, sticky=E,padx=5,pady=5)
            	Tkinter.Label(group2.interior(), text='Number of processors/cores [max. %d]: ' % (int(SERVER_max_proc[ci-1]))).grid(row=ci, column=1, sticky=W,padx=5,pady=5)
            	self.ec_top[ci] = Tkinter.Entry(group2.interior(), width=5)
            	self.ec_top[ci].insert(0, '1')
            	self.ec_top[ci].grid(row=ci, column=2,padx=5,pady=5)
            
            ci += 1
        self.vc.set('local')
        group2.grid(row=0, column=1, sticky=W,padx=5,pady=5)

       

        nb1.pack(fill='both',expand=1,padx=5,pady=5)
        nb1.setnaturalsize()

        self.dialog.activate(geometry = 'centerscreenalways')

    def setcheckbutton(self):
        if self.v_md_yes.get() == 1:
            self.v_equ_yes.set(1)
            self.v_pr_yes.set(1)
        if self.v_equ_yes.get() == 1:
            self.v_pr_yes.set(1)
            

    def apply(self, result):
        if result == 'OK':
            self.zone_radius= float(self.e1.get())
            self.net_charge = int(self.e2.get())
            self.bcc = self.v1.get()
            self.mintype = self.v0.get()
            self.min_steps = int(self.e_min.get())
            self.min_freqout = 10
            self.pr_steps = int(self.e_pr.get())
            self.pr_timestep = float(self.e_pr_dt.get())
            self.pr_freqout = int(self.e_pr_fo.get())
            self.equ_steps = int(self.e_equ.get())
            self.equ_timestep = float(self.e_equ_dt.get())
            self.equ_freqout = int(self.e_equ_fo.get())
            self.md_steps = int(self.e_md.get())
            self.md_timestep = float(self.e_md_dt.get())
            self.md_freqout = int(self.e_md_fo.get())
            self.solv_type = self.v2.get()
            self.cap_radius= float(self.e2a.get())
            self.box_dim= float(self.e2b.get())
            self.run_settings = self.v3.get()
            ci = 0
            j = str(self.vc.get())
            self.computer_name = j
            if j == 'local':
                self.local_or_server = 0
                self.amber_exe_dir = amber_dir + '/exe'
                self.numnodes = int(self.ec_top[0].get())
                self.ssh_port = 2200
                self.home_dir = '.'
            else:
                self.local_or_server = 1
                for i in SERVER_nodename:
                    if i.find(j) &gt;= 0:
                        self.amber_exe_dir = SERVER_amber_dir[ci] + '/bin'
                        self.numnodes = int(self.ec_top[ci+1].get())
                        self.ssh_port = int(SERVER_ssh_port[ci])
			self.queue_name = SERVER_queue_name[ci]
                        self.home_dir = SERVER_home_dir[ci]
                    ci += 1
            self.ok_flag = 1
            self.dialog.deactivate()
            self.dialog.withdraw()
        else:
            self.ok_flag = 0
            self.dialog.deactivate()
            self.dialog.withdraw()
#######################################################################################
class mdsimulationDialog_protein:
    def __init__(self, top):
        self.dialog = Pmw.Dialog(top,
                                 buttons = ('OK','Cancel'),
                                 defaultbutton = 'OK',
                                 title = 'Amber Plugin',
                                 command = self.apply)
                                 
        master = self.dialog.interior()

        Tkinter.Label(master, text='Specify settings for molecular dynamics simulation').pack(fill='both',expand=1,padx=5,pady=5)
        
        nb1 = Pmw.NoteBook(master)

        # restraints page
        
        restraints_page = nb1.add('Restraints')
        
        self.v0 = Tkinter.StringVar()
        self.rb_top3 = Tkinter.Radiobutton(restraints_page, text='Protein restraint outside zone', variable=self.v0, value='lig_p_zone')
        self.rb_top3.grid(row=2, column=0, sticky=W)
        self.rb_top4 = Tkinter.Radiobutton(restraints_page, text='Protein flexible', variable=self.v0, value='all')
        self.rb_top4.grid(row=3, column=0, sticky=W)

	self.v0.set('all')

	Tkinter.Label(restraints_page, text='Zone radius').grid(row=2, column=1, sticky=E)
	self.e1 = Tkinter.Entry(restraints_page, width=5)
	self.e1.insert(0, '8.0')
	self.e1.grid(row=2, column=2, sticky=W)                


        # length page
        time_page = nb1.add('Time')

	self.v_min_yes = Tkinter.IntVar()
	self.cb_min_yes = Tkinter.Checkbutton(time_page, text='Minimization', variable=self.v_min_yes, state=DISABLED, disabledforeground='black')
	self.cb_min_yes.grid(row=0, column=0, sticky=W, padx=5)
	Tkinter.Label(time_page, text='Number of minimization steps ').grid(row=0, column=1,sticky=W)
	self.e_min = Tkinter.Entry(time_page, width=10)
	self.e_min.insert(0, '500')
	self.e_min.grid(row=0, column=2)
	self.v_min_yes.set(1)

	self.v_pr_yes = Tkinter.IntVar()
	self.cb_pr_yes = Tkinter.Checkbutton(time_page, text='Equilibration (water only)', variable=self.v_pr_yes, command = self.setcheckbutton)
	self.cb_pr_yes.grid(row=1, column=0, sticky=W, padx=5)
	Tkinter.Label(time_page, text='Number of MD steps ').grid(row=1, column=1,sticky=W)
	self.e_pr = Tkinter.Entry(time_page, width=10)
	self.e_pr.insert(0, '125000')
	self.e_pr.grid(row=1, column=2)
	Tkinter.Label(time_page, text='Time step (in fs) ').grid(row=1, column=3,sticky=W)
	self.e_pr_dt = Tkinter.Entry(time_page, width=5)
	self.e_pr_dt.insert(0, '2.0')
	self.e_pr_dt.grid(row=1, column=4)
	Tkinter.Label(time_page, text='Frequency for output ').grid(row=1, column=5,sticky=W)
	self.e_pr_fo = Tkinter.Entry(time_page, width=8)
	self.e_pr_fo.insert(0, '5000')
	self.e_pr_fo.grid(row=1, column=6)
	self.v_pr_yes.set(1)

	self.v_equ_yes = Tkinter.IntVar()
	self.cb_equ_yes = Tkinter.Checkbutton(time_page, text='Equilibration', variable=self.v_equ_yes, command = self.setcheckbutton)
	self.cb_equ_yes.grid(row=2, column=0, sticky=W, padx=5)
	Tkinter.Label(time_page, text='Number of MD steps ').grid(row=2, column=1,sticky=W)
	self.e_equ= Tkinter.Entry(time_page, width=10)
	self.e_equ.insert(0, '250000')
	self.e_equ.grid(row=2, column=2)
	Tkinter.Label(time_page, text='Time step (in fs) ').grid(row=2, column=3,sticky=W)
	self.e_equ_dt = Tkinter.Entry(time_page, width=5)
	self.e_equ_dt.insert(0, '2.0')
	self.e_equ_dt.grid(row=2, column=4)
	Tkinter.Label(time_page, text='Frequency for output ').grid(row=2, column=5,sticky=W)
	self.e_equ_fo = Tkinter.Entry(time_page, width=8)
	self.e_equ_fo.insert(0, '5000')
	self.e_equ_fo.grid(row=2, column=6)
	self.v_equ_yes.set(1)

	self.v_md_yes = Tkinter.IntVar()
	self.cb_md_yes = Tkinter.Checkbutton(time_page, text='Production', variable=self.v_md_yes, command = self.setcheckbutton)
	self.cb_md_yes.grid(row=3, column=0, sticky=W, padx=5)
	Tkinter.Label(time_page, text='Number of MD steps ').grid(row=3, column=1,sticky=W)
	self.e_md= Tkinter.Entry(time_page, width=10)
	self.e_md.insert(0, '500000')
	self.e_md.grid(row=3, column=2)
	Tkinter.Label(time_page, text='Time step (in fs) ').grid(row=3, column=3,sticky=W)
	self.e_md_dt = Tkinter.Entry(time_page, width=5)
	self.e_md_dt.insert(0, '2.0')
	self.e_md_dt.grid(row=3, column=4)
	Tkinter.Label(time_page, text='Frequency for output ').grid(row=3, column=5,sticky=W)
	self.e_md_fo = Tkinter.Entry(time_page, width=8)
	self.e_md_fo.insert(0, '5000')
	self.e_md_fo.grid(row=3, column=6)
	self.v_md_yes.set(1)


        # solvation page
        solvation_page = nb1.add('Solvation')

	Tkinter.Label(solvation_page, text='Solvation method:').grid(row=0, column=0, sticky=W,padx=5,pady=5)

	self.v2 = Tkinter.StringVar()
	self.rb_solv1 = Tkinter.Radiobutton(solvation_page, text='Implicit (OBC)', variable=self.v2, value='solv_implicit')
	self.rb_solv1.grid(row=1, column=0, sticky=W,padx=5,pady=5)
	self.rb_solv2 = Tkinter.Radiobutton(solvation_page, text='Solvation cap', variable=self.v2, value='solv_cap')
	self.rb_solv2.grid(row=2, column=0, sticky=W,padx=5,pady=5)
	self.rb_solv3 = Tkinter.Radiobutton(solvation_page, text='Solvation box', variable=self.v2, value='solv_box')
	self.rb_solv3.grid(row=6, column=0, sticky=W,padx=5,pady=5)
	self.rb_solv2.select()
	self.v2.set('solv_implicit')

	Tkinter.Label(solvation_page, text='Cap radius').grid(row=2, column=1, sticky=W,padx=5,pady=5)
	self.e2a = Tkinter.Entry(solvation_page, width=5)
	self.e2a.insert(0, '25.0')
	self.e2a.grid(row=2, column=2,padx=5,pady=5)
	Label(solvation_page, text='Center, x').grid(row=3, column=1, sticky=W)
	self.e2x = Entry(solvation_page, width=5)
	self.e2x.insert(0, '%.2f' % com_x)
	self.e2x.grid(row=3, column=2)
	Label(solvation_page, text='Center, y').grid(row=4, column=1, sticky=W)
	self.e2y = Entry(solvation_page, width=5)
	self.e2y.insert(0, '%.2f' % com_y)
	self.e2y.grid(row=4, column=2)
	Label(solvation_page, text='Center, z').grid(row=5, column=1, sticky=W)
	self.e2z = Entry(solvation_page, width=5)
	self.e2z.insert(0, '%.2f' % com_z)
	self.e2z.grid(row=5, column=2)

	Tkinter.Label(solvation_page, text='Distance to boundary').grid(row=6, column=1, sticky=W,padx=5,pady=5)
	self.e2b = Entry(solvation_page, width=5)
	self.e2b.insert(0, '10.0')
	self.e2b.grid(row=6, column=2,padx=5,pady=5)


        # resource page
        resource_page = nb1.add('Resource')

        group1 = Pmw.Group(resource_page, tag_text='Project definition name')
	self.v3 = Tkinter.StringVar()
	self.rs_top1 = Tkinter.Radiobutton(group1.interior(), text='Start job in the background', variable=self.v3, value='start')
	self.rs_top1.grid(row=0, column=0, sticky=W,padx=5,pady=5)
	self.rs_top2 = Tkinter.Radiobutton(group1.interior(), text='Just prepare files for background job', variable=self.v3, value='prep')
	self.rs_top2.grid(row=1, column=0, sticky=W,padx=5,pady=5)
	self.rs_top1.select()
	self.v3.set('start')
        group1.grid(row=0, column=0, sticky=W,padx=5,pady=5)

        group2 = Pmw.Group(resource_page, tag_text='Select computer/compute cluster')
        self.rc_top = [[] for i in range(100000)]
        self.ec_top = [[] for i in range(100000)]
        self.vc = Tkinter.StringVar()
        self.rc_top[0] = Tkinter.Radiobutton(group2.interior(), text='local', variable=self.vc, value='local', indicatoron='false', width=50)
        self.rc_top[0].grid(row=0, column=0, sticky=E,padx=5,pady=5)
        Tkinter.Label(group2.interior(), text='Number of processors/cores [max. %d]: ' % (int(os.sysconf('SC_NPROCESSORS_ONLN')))).grid(row=0, column=1, sticky=W,padx=5,pady=5)
        self.ec_top[0] = Tkinter.Entry(group2.interior(), width=5)
        self.ec_top[0].insert(0, '1')
        self.ec_top[0].grid(row=0, column=2,padx=5,pady=5)
        ci = 1
        for i in SERVER_nodename:
            if ci &lt;= SERVER_number_of:
            	na = str(i)
            	self.rc_top[ci] = Tkinter.Radiobutton(group2.interior(), text=na, variable=self.vc, value=na, indicatoron='false', width=50)
            	self.rc_top[ci].grid(row=ci, column=0, sticky=E,padx=5,pady=5)
            	Tkinter.Label(group2.interior(), text='Number of processors/cores [max. %d]: ' % (int(SERVER_max_proc[ci-1]))).grid(row=ci, column=1, sticky=W,padx=5,pady=5)
            	self.ec_top[ci] = Tkinter.Entry(group2.interior(), width=5)
            	self.ec_top[ci].insert(0, '1')
            	self.ec_top[ci].grid(row=ci, column=2,padx=5,pady=5)
            
            ci += 1
        self.vc.set('local')
        group2.grid(row=0, column=1, sticky=W,padx=5,pady=5)

       

        nb1.pack(fill='both',expand=1,padx=5,pady=5)
        nb1.setnaturalsize()

        self.dialog.activate(geometry = 'centerscreenalways')
        

    def setcheckbutton(self):
        if self.v_md_yes.get() == 1:
            self.v_equ_yes.set(1)
            self.v_pr_yes.set(1)
        if self.v_equ_yes.get() == 1:
            self.v_pr_yes.set(1)
            
    def apply(self, result):
        if result == 'OK':
            self.zone_radius= float(self.e1.get())
            self.mintype = self.v0.get()
            self.min_steps = int(self.e_min.get())
            self.min_freqout = 10
            self.pr_steps = int(self.e_pr.get())
            self.pr_timestep = float(self.e_pr_dt.get())
            self.pr_freqout = int(self.e_pr_fo.get())
            self.equ_steps = int(self.e_equ.get())
            self.equ_timestep = float(self.e_equ_dt.get())
            self.equ_freqout = int(self.e_equ_fo.get())
            self.md_steps = int(self.e_md.get())
            self.md_timestep = float(self.e_md_dt.get())
            self.md_freqout = int(self.e_md_fo.get())
            self.solv_type = self.v2.get()
            self.cap_radius= float(self.e2a.get())
            self.sphere_center_x = float(self.e2x.get())
            self.sphere_center_y = float(self.e2y.get())
            self.sphere_center_z = float(self.e2z.get())
            self.box_dim= float(self.e2b.get())
            self.run_settings = self.v3.get()
            ci = 0
            j = str(self.vc.get())
            self.computer_name = j
            if j == 'local':
                self.local_or_server = 0
                self.amber_exe_dir = amber_dir + '/exe'
                self.numnodes = int(self.ec_top[0].get())
                self.ssh_port = 2200
                self.home_dir = '.'
            else:
                self.local_or_server = 1
                for i in SERVER_nodename:
                    if i.find(j) &gt;= 0:
                        self.amber_exe_dir = SERVER_amber_dir[ci] + '/bin'
                        self.numnodes = int(self.ec_top[ci+1].get())
                        self.ssh_port = int(SERVER_ssh_port[ci])
			self.queue_name = SERVER_queue_name[ci]
                        self.home_dir = SERVER_home_dir[ci]
                    ci += 1
            self.ok_flag = 1
            self.dialog.deactivate()
            self.dialog.withdraw()
        else:
            self.ok_flag = 0
            self.dialog.deactivate()
            self.dialog.withdraw()
            
#######################################################################################
class mdsimulationDialog_gromacs(tkSimpleDialog.Dialog):
	def body(self, master):
		self.ok_flag = 0

		# top level radio box to select between ligand only, ligand + protein(fixed), ligand + protein(zone), all
		self.v0 = StringVar()
		self.rb_top1 = Radiobutton(master, text='Ligand only', variable=self.v0, value='lig')
		self.rb_top1.grid(row=0, column=0, sticky=W)
		self.rb_top2 = Radiobutton(master, text='Ligand + protein, fixed', variable=self.v0, value='lig_p_fixed')
		self.rb_top2.grid(row=1, column=0, sticky=W)
		self.rb_top3 = Radiobutton(master, text='Ligand + protein, zone', variable=self.v0, value='lig_p_zone')
		self.rb_top3.grid(row=2, column=0, sticky=W)
		self.rb_top4 = Radiobutton(master, text='All', variable=self.v0, value='all')
		self.rb_top4.grid(row=3, column=0, sticky=W)
		self.rb_top2.select()
		self.v0.set('all')

		Label(master, text='Zone radius').grid(row=2, column=1, sticky=W)
		self.e1 = Entry(master, width=5)
		self.e1.insert(0, '20.0')
		self.e1.grid(row=2, column=2)

		Label(master, text=' ').grid(row=4, column=1, sticky=W)

		self.v2 = StringVar()
		self.rb_solv3 = Radiobutton(master, text='Solvation box', variable=self.v2, value='solv_box')
		self.rb_solv3.grid(row=7, column=0, sticky=W)
		self.rb_solv3.select()
		self.v2.set('solv_box')

		Label(master, text='Distance to boundary').grid(row=7, column=1, sticky=W)
		self.e2b = Entry(master, width=5)
		self.e2b.insert(0, '10.0')
		self.e2b.grid(row=7, column=2)

		Label(master, text=' ').grid(row=8, column=1, sticky=W)

		self.v_min_yes = IntVar()
		self.cb_min_yes = Checkbutton(master, text='Minimization', variable=self.v_min_yes, state=DISABLED, disabledforeground='black')
		self.cb_min_yes.grid(row=9, column=0, sticky=W, padx=5)
		Label(master, text='Number of minimization steps ').grid(row=9, column=1,sticky=W)
		self.e_min = Entry(master, width=10)
		self.e_min.insert(0, '500')
		self.e_min.grid(row=9, column=2)
		Label(master, text='Frequency for output ').grid(row=9, column=5,sticky=W)
		self.e_min_fo = Entry(master, width=8)
		self.e_min_fo.insert(0, '10')
		self.e_min_fo.grid(row=9, column=6)
		self.v_min_yes.set(1)

		self.v_pr_yes = IntVar()
		self.cb_pr_yes = Checkbutton(master, text='Equilibration (water only)', variable=self.v_pr_yes, command = self.setcheckbutton)
		self.cb_pr_yes.grid(row=10, column=0, sticky=W, padx=5)
		Label(master, text='Number of MD steps ').grid(row=10, column=1,sticky=W)
		self.e_pr= Entry(master, width=10)
		self.e_pr.insert(0, '125000')
		self.e_pr.grid(row=10, column=2)
		Label(master, text='Time step (in fs) ').grid(row=10, column=3,sticky=W)
		self.e_pr_dt = Entry(master, width=5)
		self.e_pr_dt.insert(0, '2.0')
		self.e_pr_dt.grid(row=10, column=4)
		Label(master, text='Frequency for output ').grid(row=10, column=5,sticky=W)
		self.e_pr_fo = Entry(master, width=8)
		self.e_pr_fo.insert(0, '500')
		self.e_pr_fo.grid(row=10, column=6)
		self.v_pr_yes.set(1)

		self.v_equ_yes = IntVar()
		self.cb_equ_yes = Checkbutton(master, text='Equilibration', variable=self.v_equ_yes, command = self.setcheckbutton)
		self.cb_equ_yes.grid(row=11, column=0, sticky=W, padx=5)
		Label(master, text='Number of MD steps ').grid(row=11, column=1,sticky=W)
		self.e_equ= Entry(master, width=10)
		self.e_equ.insert(0, '250000')
		self.e_equ.grid(row=11, column=2)
		Label(master, text='Time step (in fs) ').grid(row=11, column=3,sticky=W)
		self.e_equ_dt = Entry(master, width=5)
		self.e_equ_dt.insert(0, '2.0')
		self.e_equ_dt.grid(row=11, column=4)
		Label(master, text='Frequency for output ').grid(row=11, column=5,sticky=W)
		self.e_equ_fo = Entry(master, width=8)
		self.e_equ_fo.insert(0, '500')
		self.e_equ_fo.grid(row=11, column=6)
		self.v_equ_yes.set(1)

		self.v_md_yes = IntVar()
		self.cb_md_yes = Checkbutton(master, text='Production', variable=self.v_md_yes, command = self.setcheckbutton)
		self.cb_md_yes.grid(row=12, column=0, sticky=W, padx=5)
		Label(master, text='Number of MD steps ').grid(row=12, column=1,sticky=W)
		self.e_md= Entry(master, width=10)
		self.e_md.insert(0, '500000')
		self.e_md.grid(row=12, column=2)
		Label(master, text='Time step (in fs) ').grid(row=12, column=3,sticky=W)
		self.e_md_dt = Entry(master, width=5)
		self.e_md_dt.insert(0, '2.0')
		self.e_md_dt.grid(row=12, column=4)
		Label(master, text='Frequency for output ').grid(row=12, column=5,sticky=W)
		self.e_md_fo = Entry(master, width=8)
		self.e_md_fo.insert(0, '500')
		self.e_md_fo.grid(row=12, column=6)
		self.v_md_yes.set(1)

		Label(master, text=' ').grid(row=13, column=1, sticky=W)

		Label(master, text='Net charge of ligand ').grid(row=14, sticky=W)
		self.e2 = Entry(master, width=5)
		self.e2.insert(0, '0')
		self.e2.grid(row=14, column=1)

		Label(master, text='Method:').grid(row=14, column=2, sticky=W)
		self.v1 = StringVar()
		self.rb1 = Radiobutton(master, text='Gasteiger', variable=self.v1, value='gas')
		self.rb1.grid(row=14, column=3, sticky=W)
		self.rb2 = Radiobutton(master, text='AM1-BCC', variable=self.v1, value='bcc')
		self.rb2.grid(row=15, column=3, sticky=W)

		self.rb1.select()
		self.v1.set('bcc')

		Label(master, text='Number of processors ').grid(row=16, sticky=W)
		self.enp = Entry(master, width=5)
		self.enp.insert(0, '1')
		self.enp.grid(row=16, column=1)

		self.v3 = StringVar()
		self.rs_top1 = Radiobutton(master, text='Start job in the background', variable=self.v3, value='start')
		self.rs_top1.grid(row=17, column=0, sticky=W)
		self.rs_top2 = Radiobutton(master, text='Just prepare files for background job', variable=self.v3, value='prep')
		self.rs_top2.grid(row=18, column=0, sticky=W)
		self.rs_top1.select()
		self.v3.set('start')

                
		return self.e1 # initial focus

	def validate(self):
 		try:
			self.zone_radius= float(self.e1.get())
			self.net_charge = int(self.e2.get())
			self.bcc = self.v1.get()
			self.mintype = self.v0.get()
			self.min_steps = int(self.e_min.get())
			self.min_freqout = int(self.e_min_fo.get())
			self.pr_steps = int(self.e_pr.get())
			self.pr_timestep = float(self.e_pr_dt.get())
			self.pr_freqout = int(self.e_pr_fo.get())
			self.equ_steps = int(self.e_equ.get())
			self.equ_timestep = float(self.e_equ_dt.get())
			self.equ_freqout = int(self.e_equ_fo.get())
			self.md_steps = int(self.e_md.get())
			self.md_timestep = float(self.e_md_dt.get())
			self.md_freqout = int(self.e_md_fo.get())
			self.solv_type = self.v2.get()
			self.box_dim= float(self.e2b.get())
                        self.run_settings = self.v3.get()
			self.num_proc = int(self.enp.get())
			return 1

		except ValueError:
			tkMessageBox.showwarning(
				'Bad input',
				'Illegal values, please try again'
			)
			return 0

	def setcheckbutton(self):
                if self.v_md_yes.get() == 1:
                    self.v_equ_yes.set(1)
                    self.v_pr_yes.set(1)
                if self.v_equ_yes.get() == 1:
                    self.v_pr_yes.set(1)
            
	def apply(self):
		self.zone_radius= float(self.e1.get())
		self.net_charge = int(self.e2.get())
		self.bcc = self.v1.get()
		self.mintype = self.v0.get()
		self.min_steps = int(self.e_min.get())
                self.min_freqout = int(self.e_min_fo.get())
		self.pr_steps = int(self.e_pr.get())
		self.pr_timestep = float(self.e_pr_dt.get())
                self.pr_freqout = int(self.e_pr_fo.get())
		self.equ_steps = int(self.e_equ.get())
		self.equ_timestep = float(self.e_equ_dt.get())
                self.equ_freqout = int(self.e_equ_fo.get())
		self.md_steps = int(self.e_md.get())
		self.md_timestep = float(self.e_md_dt.get())
                self.md_freqout = int(self.e_md_fo.get())
		self.solv_type = self.v2.get()
		self.box_dim= float(self.e2b.get())
                self.run_settings = self.v3.get()
                self.num_proc = int(self.enp.get())

		self.ok_flag = 1

	def cancel(self, event=None):
		# put focus back to the parent window
		self.parent.focus_set()
		self.destroy()


#######################################################################################
class ModelessMessage(Toplevel):
    def __init__(self,master,text):
        Toplevel.__init__(self,master)
        self.transient(master)
        self.parent = master
        body = Frame(self)

        self.text = text
        Label( self , text=str(self.text) ).pack()

        self.initial_focus = self.body(body)
        body.pack(padx=5, pady=5)
        self.grab_set()
        if not self.initial_focus:
            self.initial_focus = self
        self.protocol('WM_DELETE_WINDOW', self.cancel)
        self.geometry('+%d+%d' % (master.winfo_rootx()+50, master.winfo_rooty()+50))
        self.initial_focus.focus_set()
        self.grab_release()
        self.wait_window(self)	

    def cancel(self,event=None):
        self.destroy()



#######################################################################################
def minim_lig_prot(app):
	d_min_lig = minimLig_dialog(app.root)
	if d_min_lig.ok_flag == 0 or d_min_lig.object_name_lig == '' or d_min_lig.object_name_prot == '':
		return 0
	# write ligand to mol2 file
#	cmd.select('pro', 'usersel and resn ALA+ARG+ASH+ASN+ASP+CYS+CYX+CY1+GLH+GLN+GLU+GLY+HIS+HIE+HID+HIP+ILE+LEU+LYS+MET+PHE+PRO+SER+THR+TRP+TYR+VAL')
#	cmd.delete('pro')
	w = minimizationDialog(app.root)
	if w.ok_flag == 0:
		return 0

        # find number of object in list
        object_list = []
        for na in cmd.get_names('objects'):
            try:
                object_list.append(na)
            except:
                pass


        cmd.select('usersel', d_min_lig.object_name_lig)
	write_mol2('usersel', 'tmp')

        
        L = cmd.count_atoms('usersel')
	if L == 0:
		tkMessageBox.showwarning('Could not find any selected atoms','Please select ligand before running minimization.')
		return 0
	
        

        # resname of ligand
	stored.resname = []
	cmd.iterate ('usersel', 'stored.resname.append(resn)')

	tmp_ligname = []
	tmp_ligname = stored.resname[0][0:3]

# write leapL.in and run tleap on ligand
	fout = open('leapL.in','w')
	fout.write('source leaprc.gaff\n')
	fout.write('loadamberprep tmp.prepin\n')
	fout.write('saveoff ' + tmp_ligname + ' tmp.lib\n')
	fout.write('quit\n')
	fout.close()

	
	# run antechamber and parmchk
        fcom = open('RunCommands', 'w')
        fcom.write('%s/exe/antechamber -i tmp.mol2 -fi mol2 -o tmp.prepin -fo prepi -c %s -nc %s\n' % (amber_dir, w.bcc, str(w.net_charge)))
        fcom.write('if [ ! -f tmp.prepin ]; then\n')
        fcom.write('  %s/exe/antechamber -i tmp.mol2 -fi mol2 -o tmp.prepin -fo prepi -c bcc -nc %s\n' % (amber_dir, str(w.net_charge)))
        fcom.write('fi\n')
        fcom.write('if [ ! -f tmp.prepin ]; then\n')
        fcom.write('  %s/exe/antechamber -i tmp.mol2 -fi mol2 -o tmp.prepin -fo prepi -c gas -nc %s\n' % (amber_dir, str(w.net_charge)))
        fcom.write('fi\n')
        fcom.write('%s/exe/parmchk -i tmp.prepin -f prepi -o tmp.frcmod\n' % (amber_dir))
        fcom.write('%s/exe/tleap -f leapL.in\n' % (amber_dir))
        fcom.close()
        
#        message = ModelessMessage(app.root, 'Preparing ligand. This may take seconds to minutes dependent on size fo ligand and charge calculation protocol.')
        
	os.system('mkdir tmp_amber')
	os.system('cp tmp.mol2 RunCommands leapL.in ./tmp_amber/')
	os.system('cd ./tmp_amber; chmod a+rwx RunCommands; ./RunCommands')
	os.system('cp ./tmp_amber/NEWPDB.PDB ./tmp_amber/tmp.* .')
        
#        message.cancel()
        
	if os.path.exists('tmp.lib') == 0:
		tkMessageBox.showwarning('Problem in ligand preparation', 'Please check structure and net charge of ligand.\n Are hydrogens added?')
		return 0
	os.system('rm -rf tmp_amber')

 
# generate leapP.in file
# ligand only
	if w.mintype == 'lig':
		fout = open('leapP.in','w')
		fout.write('source leaprc.gaff\n')
		fout.write('source leaprc.ff03\n')
		fout.write('loadoff tmp.lib\n')
		fout.write('flig = loadamberparams tmp.frcmod\n')
		fout.write('prot = loadpdb prot_lig.pdb\n')
                if w.solvation == 'obc':
                    fout.write('set default PBradii mbondi2\n')
		fout.write('saveoff prot prot.lib\n')
		fout.write('saveamberparm prot prot.top prot.trj\n')
		fout.write('quit\n')
		fout.close()
                hem_flag = 0
                fad_flag = 0
                shutil.copy('NEWPDB.PDB', 'prot_lig.pdb')
# ligand + protein
	else:
		stored.chain = []
		stored.resnam = []
		stored.resid = []
                cof_flag = []
		for na in cmd.get_names('objects'):
                    try:
                        if na == d_min_lig.object_name_prot:
                            cmd.select('pro', na)
                            cmd.select('pro2', 'pro and resn %s' % PDBcode_protein)
                            # check for co-factors
                            cf = 0
                            for pco, fco in zip(PDBcode_cofactors, filename_cofactors):
                                cmd.select('pro3', 'pro and resn %s' % pco)
                                if cmd.count_atoms('pro3') &gt; 0:
                                    cof_flag.append(cf)
                                cf += 1
                                cmd.delete('pro3')
                            cmd.select('pro4', 'pro and not resn %s' % PDBcode_protein_water)
                            L = cmd.count_atoms('pro4')
                            if L &gt; 0:
                                stored.list = []
                                cmd.iterate('pro4', 'stored.list.append((resi, resn))')
                                # remove duplicates
                                du = {}
                                for uu in stored.list:
                                    du[uu] = uu
                                fin_list = du.values()
                                fin_list.sort()
                                strg1 = ''
                                for sa, sb in fin_list:
                                    strg1 += '%s %s  ' % (sa, sb)
                                strg2 = 'The following residues are unknown by the force field: %s \n\n Please separate ligand into different object and/or define co-factors in folder %s' % (strg1, library_dir)    
                                
                                tkMessageBox.showwarning('Unknown residues', strg2)
                                cmd.delete('pro')
                                cmd.delete('pro2')
                                cmd.delete('pro4')
                                return 0
                            cmd.delete('pro4')

                            L = cmd.count_atoms('pro2')
                            if L &gt; 0:
                                    rem = na
                                    find_disulfide_bridges('pro2') 
                                    cmd.select('sele2', 'pro and name CA+FE')
                                    cmd.iterate ('sele2', 'stored.chain.append(chain)')
                                    cmd.iterate ('sele2', 'stored.resnam.append(resn)')
                                    cmd.iterate ('sele2', 'stored.resid.append(resi)')
                                    cmd.save('prot_out.pdb','pro', 0, 'pdb')
                                    find_disulfide_bridges_2('prot_out.pdb', cof_flag, '000')
                                    # read first residue number in prot_out.pdb file for proper disulfide numbering
                                    for line in open('prot_out.pdb'):
                                        if line.find('ATOM') &gt;= 0:
                                            resid_zero = int(line[22:26].strip())
                                            break
                                    ResortPDB4Amber('prot_out.pdb') 
                            else:
                                return 0
                            cmd.delete('pro')
                            cmd.delete('pro2')
                    
                    except:
                        pass
        
                # concatenate ligand and protein
		datalist = []
		for line in open('NEWPDB.PDB'):
			datalist.append(line)
		datalist.append('TER\n')
		for line in open('prot_out.pdb'):
                    if line[13:16] != 'H1 ' and line[13:16] != 'H2 ' and line[13:16] != 'H3 ' and line[13:16] != 'OXT':
			datalist.append(line)
		fout = open('prot_lig.pdb', 'w')
		fout.writelines(datalist)
		fout.close()
                
                # for energy analysis (MMPBSA)
                if w.v_enout_yes.get() == 1:
                    # ligand only
                    shutil.copy('NEWPDB.PDB', 'lig_only.pdb')
                    fout = open('leapP_lig_only.in','w')
                    fout.write('source leaprc.gaff\n')
                    fout.write('source leaprc.ff03\n')
                    fout.write('loadoff tmp.lib\n')
                    fout.write('flig = loadamberparams tmp.frcmod\n')
                    fout.write('prot = loadpdb lig_only.pdb\n')
                    if w.solvation == 'obc':
                        fout.write('set default PBradii mbondi2\n')
                    fout.write('saveoff prot lig_only.lib\n')
                    fout.write('saveamberparm prot lig_only.top lig_only.trj\n')
                    fout.write('quit\n')
                    fout.close()
                    
                    # protein only
                    datalist = []
                    for line in open('prot_out.pdb'):
                        if line[13:16] != 'H1 ' and line[13:16] != 'H2 ' and line[13:16] != 'H3 ' and line[13:16] != 'OXT':
                            datalist.append(line)
                    fout = open('prot_only.pdb', 'w')
                    fout.writelines(datalist)
                    fout.close()
                    # read first residue number in prot_out.pdb file for proper disulfide numbering
                    for line in open('prot_out.pdb'):
                        if line.find('ATOM') &gt;= 0:
                            resid_zero = int(line[22:26].strip())
                            break
                    # write leapP_prot_only.in
                    fout = open('leapP_prot_only.in','w')
                    fout.write('source leaprc.ff03\n')
                    for j in cof_flag:
                        fout.write('loadoff %s.lib\n' % (filename_cofactors[j]))
                        fout.write('fcof = loadamberparams %s.frcmod\n' % (filename_cofactors[j]))
                    fout.write('prot = loadpdb prot_only.pdb\n')
                    # add disulfide bridges
                    for ds1_i, ds1_n, ds1_a, ds2_i, ds2_n, ds2_a in zip(disulfide_A, disulfide_A_name, disulfide_A_atom, disulfide_B, disulfide_B_name, disulfide_B_atom):
                        fout.write('bond prot.%d.%s prot.%d.%s\n' % (int(ds1_i)+resid_zero-1, ds1_a, int(ds2_i)+resid_zero-1, ds2_a))
                    if w.solvation == 'obc':
                        fout.write('set default PBradii mbondi2\n')
                    fout.write('saveoff prot prot_only.lib\n')
                    fout.write('saveamberparm prot prot_only.top prot_only.trj\n')
                    fout.write('quit\n')
                    fout.close()

                # write leapP.in
                # read first residue number in prot_out.pdb file for proper disulfide numbering
                for line in open('prot_lig.pdb'):
                    if line.find('ATOM') &gt;= 0:
                        resid_zero = int(line[22:26].strip())
                        break
		fout = open('leapP.in','w')
		fout.write('source leaprc.gaff\n')
		fout.write('source leaprc.ff03\n')
		fout.write('loadoff tmp.lib\n')
		fout.write('flig = loadamberparams tmp.frcmod\n')
                for j in cof_flag:
                    fout.write('loadoff %s.lib\n' % (filename_cofactors[j]))
                    fout.write('fcof = loadamberparams %s.frcmod\n' % (filename_cofactors[j]))
		fout.write('prot = loadpdb prot_lig.pdb\n')
                # add disulfide bridges
                for ds1_i, ds1_n, ds1_a, ds2_i, ds2_n, ds2_a in zip(disulfide_A, disulfide_A_name, disulfide_A_atom, disulfide_B, disulfide_B_name, disulfide_B_atom):
                    fout.write('bond prot.%d.%s prot.%d.%s\n' % (int(ds1_i)+resid_zero, ds1_a, int(ds2_i)+resid_zero, ds2_a))
                if w.solvation == 'obc':
                    fout.write('set default PBradii mbondi2\n')
		fout.write('saveoff prot prot.lib\n')
		fout.write('saveamberparm prot prot.top prot.trj\n')
		fout.write('quit\n')
		fout.close()


	# write min.in
	fout = open('min.in','w')
	fout.write('initial minimisation\n')
	fout.write(' &amp;cntrl\n')
	fout.write('  imin   = 1,\n')
	fout.write('  ntmin   = 0,\n')
	fout.write('  maxcyc = %d,\n' % (w.min_steps))
	fout.write('  ncyc   = %d,\n' % (w.min_steps/2))
	fout.write('  ntpr   = 10,\n')
	fout.write('  ntb    = 0,\n')
        if w.solvation == 'ddd':
            fout.write('  igb    = 0,\n')
        else:
            fout.write('  igb    = 2,\n')
	fout.write('  cut    = 12,\n')
	if w.mintype == 'lig_p_fixed' or w.mintype == 'lig_p_zone':
		fout.write('  ntr    = 1, restraint_wt = 500.0,\n')
	if w.mintype == 'lig_p_fixed':
		fout.write('  restraintmask = \'(:1 &gt; :0.01)\',\n')
	if w.mintype == 'lig_p_zone':
		fout.write('  restraintmask = \'(:1 &gt;:%f)\',\n' % (w.zone_radius))
	fout.write(' /\n')
        if w.solvation == 'ddd':
            fout.write(' &amp;ewald\n')
            fout.write('  eedmeth = 5,\n')
            fout.write(' /\n')
	fout.close()

	# run tleap on complex
        fcom = open('RunCommands', 'w')
        fcom.write('%s/exe/tleap -f leapP.in\n' % (amber_dir))
        if w.v_enout_yes.get() == 1:
            fcom.write('%s/exe/tleap -f leapP_prot_only.in\n' % (amber_dir))
            fcom.write('%s/exe/tleap -f leapP_lig_only.in\n' % (amber_dir))
        fcom.write('sander -O -i min.in -p prot.top -c prot.trj -o prot.out -r prot.rst -ref prot.trj\n')
        fcom.write('%s/exe/ambpdb -p prot.top -aatm &lt; prot.rst &gt; prot_fin.pdb\n' % (amber_dir))
        fcom.write('%s/exe/ptraj prot.top &lt;&lt; EOF\n' % (amber_dir))
        fcom.write('   trajin prot.rst\n')
        fcom.write('   trajout min.trj nobox\n')
        fcom.write('EOF\n')
        fcom.close()

        os.system('mkdir tmp_amber')
        if w.v_enout_yes.get() == 1:
            os.system('cp prot_lig.pdb prot_only.pdb lig_only.pdb tmp.lib tmp.frcmod leapP*in min.in RunCommands ./tmp_amber/')
        else:
            os.system('cp prot_lig.pdb tmp.lib tmp.frcmod leapP.in min.in RunCommands ./tmp_amber/')
        for j in cof_flag:
            os.system('cp %s/%s.lib %s/%s.frcmod ./tmp_amber/' % (library_dir, filename_cofactors[j], library_dir, filename_cofactors[j]))
	# run minimization
	# generate pdb file for final structure
	os.system('cd ./tmp_amber; chmod u+rwx RunCommands; ./RunCommands')

	os.system('cp ./tmp_amber/prot_fin.pdb ./tmp_amber/prot.top .')
   
	if os.path.exists('prot_fin.pdb') == 0:
		tkMessageBox.showwarning('Problem in energy minimization','Please check initial structure of protein-ligand complex.')
		return 0

	# array of atom names
	stored.atname = []
	cmd.iterate ('usersel', 'stored.atname.append(name)')
#	print stored.atname
	# array for coordinates
	stored.sel = []
	cmd.iterate_state(1, 'usersel', 'stored.sel.append([x,y,z])')
#	print stored.sel

	# split pdb file in ligand and protein
	flag_lig = 1 
	fin = open('prot_fin.pdb', 'r')
	fout = open('tmp_fin.pdb', 'w')
	for line in fin:
		if flag_lig == 0:
			fout.write(line) 
		if line[0:3] == 'TER':
			flag_lig = 0    
	fin.close() 
	fout.close() 

   
     
	# update ligand coordinates (new atom order)
	atnam = []
	tmp_str = []
	fin = open('prot_fin.pdb', 'r')
	str1 = fin.read()
	for line in str1.split('\n'):
		if len(line) &gt; 10 and line[0:4] == 'ATOM' and line[23:26] == '  1':
			if line[13] != ' ':
				if line[14] != ' ':
					if line[15] != ' ':
						atnam = line[12] + line[13] + line[14] + line[15]
					else:
						atnam = line[12] + line[13] + line[14]
				else:
					atnam = line[12] + line[13]
			else:
				atnam = line[12]

			xx = float(line[30:38])
			yy = float(line[38:46])
			zz = float(line[46:54])

			j = 0
			for i in stored.atname:
				if i == atnam:
					stored.sel[j][0] = xx
					stored.sel[j][1] = yy
					stored.sel[j][2] = zz
#					print '%s %d %f %f %f' % (i, j, xx, yy, zz)
				j = j + 1
	fin.close() 

	# update coordinates
	cmd.alter_state(1,'usersel','(x,y,z)=stored.sel.pop(0)')

	my_view= cmd.get_view()

	if w.mintype != 'lig':
		cmd.load('tmp_fin.pdb', rem)
		cmd.split_states(rem)
 		cmd.delete(name=rem)
		cmd.delete('%s_0001' % (rem))
                tmp_obj = rem + '_0002'
   
		# reset residue numbers
		stored.chain2 = []
		stored.resnam2 = []
		stored.resid2 = []
		for na in cmd.get_names('objects'):
                    try:
                        if na == tmp_obj:
                            cmd.select('pro', na)
                            cmd.select('pro2', 'pro and resn %s' % PDBcode_protein)
                            L = cmd.count_atoms('pro2')
                            if L &gt; 0:
                                    cmd.iterate ('pro2', 'stored.chain2.append(chain)')
                                    cmd.iterate ('pro2', 'stored.resnam2.append(resn)')
                                    cmd.iterate ('pro2', 'stored.resid2.append(resi)')
                                    ci = 0
                                    k = 0 
                                    oldresid = int(stored.resid2[0]) 
                                    for i in stored.resid2:
                                            j = int(i) 
                                            if j &gt; oldresid:
                                                    ci = ci + 1
                                                    oldresid = j
                                            stored.resid2[k] = stored.resid[ci]
                                            stored.chain2[k] = stored.chain[ci]
                                            k = k + 1 
                                    cmd.alter('pro2','resi=str(stored.resid2.pop(0))')
                                    cmd.alter('pro2','chain=str(stored.chain2.pop(0))')
                                    cmd.disable(na)
                                    cmd.enable(na)  
                                    cmd.set_name(na, rem)   
             
                    
                            cmd.delete('pro')
                            cmd.delete('pro2')
                    except:
                        pass

        # resort list of objects
        for obj in object_list:
            for na in cmd.get_names('objects'):
                try:
                    if na == obj:
                        cmd.copy('tmp_obj', na)
                        cmd.delete(na)
                        cmd.set_name('tmp_obj', na)   
                except:
                    pass
                
	cmd.set_view(my_view)


	if w.mintype != 'lig' and w.v_sie_yes.get() == 1:
            # determine protein-ligand interactions
            ftop = open('prot.top', 'r')
            ftop.seek(0)
            while ftop:
                line = ftop.readline()
                if line.find('FLAG POINTERS') &gt; -1:
                    ftop.readline()
                    line = ftop.readline()
                    break
            end_protein = int(line[0:8])
            
            ftop.seek(0)
            while ftop:
                line = ftop.readline()
                if line.find('FLAG RESIDUE_POINTER') &gt; -1:
                    ftop.readline()
                    line = ftop.readline()
                    break
            start_lig_id = int(line[0:8])
            end_lig_id = int(line[8:16])-1
            
            ftop.close()

            fcom = open('RunSIE', 'w')
            fcom.write('%s/bin/sietraj -pt prot.top -trj min.trj -sf 1 -ef 1 -inc 1 -tr %d-%d -lr %d-%d -o sie.out -sie\n' % (sie_dir, end_lig_id+1, end_protein, start_lig_id, end_lig_id))
            fcom.write('%s/bin/sietraj -ave sie.out &gt; sie_ave.out\n' % (sie_dir))
            fcom.close()
            
            
            os.system('cp RunSIE ./tmp_amber/')
            os.system('cd ./tmp_amber; chmod u+rwx RunSIE; ./RunSIE')
            os.system('cp ./tmp_amber/sie* .')
            
            sie_results(app.root)

	if w.mintype != 'lig' and w.v_enout_yes.get() == 1:
            # determine protein-ligand potential energy
            ftop = open('prot.top', 'r')
            ftop.seek(0)
            while ftop:
                line = ftop.readline()
                if line.find('FLAG POINTERS') &gt; -1:
                    ftop.readline()
                    line = ftop.readline()
                    break
            end_protein = int(line[0:8])
            
            ftop.seek(0)
            while ftop:
                line = ftop.readline()
                if line.find('FLAG RESIDUE_POINTER') &gt; -1:
                    ftop.readline()
                    line = ftop.readline()
                    break
            start_lig_id = int(line[0:8])
            end_lig_id = int(line[8:16])-1
            
            ftop.close()
            
            # write mmbpsa_snap.in file
            fmmpbsa = open('mmpbsa_snap.in', 'w')
            fmmpbsa.write('#############################\n')
            fmmpbsa.write('@GENERAL\n')
            fmmpbsa.write('#\n')
            fmmpbsa.write('PREFIX                snapshot\n')
            fmmpbsa.write('PATH                  ./\n')
            fmmpbsa.write('#\n')
            fmmpbsa.write('COMPLEX               1\n')
            fmmpbsa.write('RECEPTOR              1\n')
            fmmpbsa.write('LIGAND                1\n')
            fmmpbsa.write('#\n')
            fmmpbsa.write('COMPT                 ./prot.top\n')
            fmmpbsa.write('RECPT                 ./prot_only.top\n')
            fmmpbsa.write('LIGPT                 ./lig_only.top\n')
            fmmpbsa.write('#\n')
            fmmpbsa.write('GC                    1\n')
            fmmpbsa.write('AS                    0\n')
            fmmpbsa.write('DC                    0\n')
            fmmpbsa.write('#\n')
            fmmpbsa.write('MM                    0\n')
            fmmpbsa.write('GB                    0\n')
            fmmpbsa.write('PB                    0\n')
            fmmpbsa.write('MS                    0\n')
            fmmpbsa.write('#\n')
            fmmpbsa.write('NM                    0\n')
            fmmpbsa.write('#\n')
            fmmpbsa.write('################################################################################\n')
            fmmpbsa.write('@MAKECRD\n')
            fmmpbsa.write('#\n')
            fmmpbsa.write('#\n')
            fmmpbsa.write('BOX                   NO\n')
            fmmpbsa.write('NTOTAL                %d\n' % (end_protein))
            fmmpbsa.write('NSTART                1\n')
            fmmpbsa.write('NSTOP                 1\n')
            fmmpbsa.write('NFREQ                 1\n')
            fmmpbsa.write('#\n')
            fmmpbsa.write('NUMBER_LIG_GROUPS     1\n')
            fmmpbsa.write('LSTART                %d\n' % (start_lig_id))
            fmmpbsa.write('LSTOP                 %d\n' % (end_lig_id))
            fmmpbsa.write('NUMBER_REC_GROUPS     1\n')
            fmmpbsa.write('RSTART                %d\n' % (end_lig_id+1))
            fmmpbsa.write('RSTOP                 %d\n' % (end_protein))
            fmmpbsa.write('#\n')
            fmmpbsa.write('#################################################################################\n')
            fmmpbsa.write('@TRAJECTORY\n')
            fmmpbsa.write('#\n')
            fmmpbsa.write('TRAJECTORY            ./min.trj\n')
            fmmpbsa.write('#\n')
            fmmpbsa.write('################################################################################\n')
            fmmpbsa.write('@PROGRAMS\n')
            fmmpbsa.write('#\n')
            fmmpbsa.write('################################################################################\n')
            fmmpbsa.close()

            # write mmbpsa_dg.in file
            fmmpbsa = open('mmpbsa_dg.in', 'w')
            fmmpbsa.write('#############################\n')
            fmmpbsa.write('@GENERAL\n')
            fmmpbsa.write('#\n')
            fmmpbsa.write('PREFIX                snapshot\n')
            fmmpbsa.write('PATH                  ./\n')
            fmmpbsa.write('#\n')
            fmmpbsa.write('COMPLEX               1\n')
            fmmpbsa.write('RECEPTOR              1\n')
            fmmpbsa.write('LIGAND                1\n')
            fmmpbsa.write('#\n')
            fmmpbsa.write('COMPT                 ./prot.top\n')
            fmmpbsa.write('RECPT                 ./prot_only.top\n')
            fmmpbsa.write('LIGPT                 ./lig_only.top\n')
            fmmpbsa.write('#\n')
            fmmpbsa.write('GC                    0\n')
            fmmpbsa.write('AS                    0\n')
            fmmpbsa.write('DC                    0\n')
            fmmpbsa.write('#\n')
            fmmpbsa.write('MM                    1\n')
            fmmpbsa.write('GB                    0\n')
            if w.v_incsolv_yes.get() == 1:
                fmmpbsa.write('PB                    1\n')
                fmmpbsa.write('MS                    1\n')
            else:
                fmmpbsa.write('PB                    0\n')
                fmmpbsa.write('MS                    0\n')
            fmmpbsa.write('#\n')
            fmmpbsa.write('NM                    0\n')
            fmmpbsa.write('#\n')
            if w.v_incsolv_yes.get() == 1:
                fmmpbsa.write('################################################################################\n')
                fmmpbsa.write('@PB\n')
                fmmpbsa.write('#\n')
                fmmpbsa.write('PROC                  2\n')
                fmmpbsa.write('REFE                  0\n')
                fmmpbsa.write('INDI                  1.0\n')
                fmmpbsa.write('EXDI                  80.0\n')
                fmmpbsa.write('SCALE                 2\n')
                fmmpbsa.write('LINIT                 1000\n')
                fmmpbsa.write('PRBRAD                1.4\n')
                fmmpbsa.write('ISTRNG                0.0\n')
                fmmpbsa.write('RADIOPT               0\n')
                fmmpbsa.write('NPOPT                 1\n')
                fmmpbsa.write('CAVITY_SURFTEN        0.0072\n')
                fmmpbsa.write('CAVITY_OFFSET         0.00\n')
                fmmpbsa.write('#\n')
                fmmpbsa.write('SURFTEN               0.0072\n')
                fmmpbsa.write('SURFOFF               0.00\n')
                fmmpbsa.write('#\n')
            fmmpbsa.write('################################################################################\n')
            fmmpbsa.write('@MM\n')
            fmmpbsa.write('#\n')
            fmmpbsa.write('DIELC                 1.0\n')
            fmmpbsa.write('#\n')
            fmmpbsa.write('################################################################################\n')
            if w.v_incsolv_yes.get() == 1:
                fmmpbsa.write('@MS\n')
                fmmpbsa.write('#\n')
                fmmpbsa.write('# Molsurf parameters (this section is only relevant if MS = 1 above)\n')
                fmmpbsa.write('#\n')
                fmmpbsa.write('#   PROBE - Radius of the probe sphere used to calculate the SAS.\n')
                fmmpbsa.write('#           Since Bondi radii are already augmented by 1.4A, PROBE should be 0.0\n')
                fmmpbsa.write('#\n')
                fmmpbsa.write('PROBE                 0.0\n')
                fmmpbsa.write('#\n')
                fmmpbsa.write('#################################################################################\n')
            fmmpbsa.write('@PROGRAMS\n')
            fmmpbsa.write('#\n')
            fmmpbsa.write('################################################################################\n')
            fmmpbsa.close()

            fcom = open('RunMMPBSA', 'w')
            fcom.write('mm_pbsa.pl mmpbsa_snap.in &gt; mmpbsa_snap.log\n')
            fcom.write('mm_pbsa.pl mmpbsa_dg.in &gt; mmpbsa_dg.log\n')
            fcom.close()
            
            
            os.system('cp RunMMPBSA mmpbsa*.in ./tmp_amber/')
            os.system('cd ./tmp_amber; chmod u+rwx RunMMPBSA; ./RunMMPBSA')
            os.system('cp ./tmp_amber/snapshot_statistics.out .')
            
            mmpbsa_results(app.root)


	os.system('rm -rf tmp_amber')
  
	if w.mintype != 'lig':
            os.remove('prot_out.pdb')
	os.remove('prot_fin.pdb')
	os.remove('prot_lig.pdb')
	os.remove('leapL.in')
	os.remove('leapP.in')
	os.remove('RunCommands')
	os.remove('tmp.prepin')
	os.remove('tmp.frcmod')
	os.remove('tmp.lib')
#	os.remove('tmp.mol')
	os.remove('tmp.mol2')
	os.remove('min.in')
	os.remove('NEWPDB.PDB')
	os.remove('prot.top')
	os.remove('tmp_fin.pdb')

        if w.v_enout_yes.get() == 1:
            os.remove('prot_only.pdb')
            os.remove('lig_only.pdb')
            os.remove('RunMMPBSA')
            os.remove('mmpbsa_snap.in')
            os.remove('mmpbsa_dg.in')
            os.remove('leapP_prot_only.in')
            os.remove('leapP_lig_only.in')
            os.remove('snapshot_statistics.out')
	print('minimization done')



#######################################################################################
def md_simulation(app, md_program):
        # find number of object in list
        object_list = []
        for na in cmd.get_names('objects'):
            try:
                object_list.append(na)
            except:
                pass

        # select protein and ligand object
	d_md_lig = minimLig_dialog(app.root)
	if d_md_lig.ok_flag == 0 or d_md_lig.object_name_lig == '' or d_md_lig.object_name_prot == '':
		return 0

        # select directory for project
        d_md_dir = saveDialog(app.root)
	if d_md_dir.ok_flag == 0:
		return

	md_outfile = d_md_dir.project_dir + '_client'
	md_save_project = 1

        # create project directory and delete old files (if existing)
	if os.path.isdir(md_outfile):
            for af in os.listdir(md_outfile):
                possible_dir = md_outfile + '/%s' % (af)
#                print 'aaa %s %s' % (af, possible_dir)
                if os.path.isdir(possible_dir):
#                    print 'bbb %s' % (af)
                    for bf in os.listdir(possible_dir):
                        os.remove('%s/%s' % (possible_dir, bf))
                    os.rmdir(possible_dir)
                else:
#                    print 'ccc %s' % (af)
                    os.remove('%s/%s' % (md_outfile, af))
            os.rmdir(md_outfile)
        os.mkdir(md_outfile)

	curdir = os.getcwd()

        # change into project directory
        os.chdir(md_outfile)





	# write ligand to pdb file
        cmd.select('usersel', d_md_lig.object_name_lig)
	write_mol2('usersel', 'tmp')

        
        L = cmd.count_atoms('usersel')
	if L == 0:
		tkMessageBox.showwarning('Could not find any ligand', 'Please select ligand before running minimization.')
		return 0


        # specify MM settings
        if md_program == 'amber':
            wmd = mdsimulationDialog(app.root)
        else:
            wmd = mdsimulationDialog_gromacs(app.root)

	if wmd.ok_flag == 0:
		return 0
                
#        print '%d %d %s %s' % (wmd.numnodes, wmd.local_or_server, wmd.computer_name, wmd.amber_exe_dir)
#        return 0

        # resname of ligand
	stored.resname = []
	cmd.iterate ('usersel', 'stored.resname.append(resn)')

	tmp_ligname = []
	tmp_ligname = stored.resname[0][0:3]

        # write leapL.in and run tleap on ligand
	fout = open('leapL.in','w')
	fout.write('source leaprc.gaff\n')
	fout.write('loadamberprep tmp.prepin\n')
	fout.write('saveoff ' + tmp_ligname + ' tmp.lib\n')
	fout.write('quit\n')
	fout.close()

	
	# run antechamber and parmchk
        fcom = open('RunCommands', 'w')
        fcom.write('dos2unix tmp.mol2\n')
        fcom.write('dos2unix leapL.in\n')
        fcom.write('%s/exe/antechamber -i tmp.mol2 -fi mol2 -o tmp.prepin -fo prepi -c %s -nc %s\n' % (amber_dir, wmd.bcc, str(wmd.net_charge)))
        fcom.write('if [ ! -f tmp.prepin ]; then\n')
        fcom.write('  %s/exe/antechamber -i tmp.mol2 -fi mol2 -o tmp.prepin -fo prepi -c bcc -nc %s\n' % (amber_dir, str(wmd.net_charge)))
        fcom.write('fi\n')
        fcom.write('if [ ! -f tmp.prepin ]; then\n')
        fcom.write('  %s/exe/antechamber -i tmp.mol2 -fi mol2 -o tmp.prepin -fo prepi -c gas -nc %s\n' % (amber_dir, str(wmd.net_charge)))
        fcom.write('fi\n')
        fcom.write('%s/exe/parmchk -i tmp.prepin -f prepi -o tmp.frcmod\n' % (amber_dir))
        fcom.write('%s/exe/tleap -f leapL.in\n' % (amber_dir))
        fcom.close()
        
#	os.system('mkdir %s' % (d_md_dir.project_dir_short))
#	os.system('cp tmp.mol2 RunCommands leapL.in ./%s/' % (d_md_dir.project_dir_short))
#	os.system('cd ./%s; chmod u+rwx RunCommands; ./RunCommands' % (d_md_dir.project_dir_short))
	os.system('chmod u+rwx RunCommands; ./RunCommands')
#	os.system('cp ./%s/NEWPDB.PDB ./%s/tmp.* .' % (d_md_dir.project_dir_short, d_md_dir.project_dir_short))
        
	if os.path.exists('tmp.lib') == 0:
		tkMessageBox.showwarning('Problem in ligand preparation', 'Please check structure and net charge of ligand.')
		return 0
#	os.system('rm -rf %s' % (d_md_dir.project_dir_short))

	# generate leapP.in file
	# ligand only
	if wmd.mintype == 'lig':
                cof_flag = []
		fout = open('leapP.in','w')
		fout.write('source leaprc.gaff\n')
		fout.write('source leaprc.ff03\n')
		fout.write('loadoff tmp.lib\n')
		fout.write('flig = loadamberparams tmp.frcmod\n')
		fout.write('prot = loadpdb NEWPDB.PDB\n')
		fout.write('saveoff prot prot.lib\n')
		fout.write('saveamberparm prot prot.top prot.crd\n')
		fout.write('quit\n')
		fout.close()
	# ligand + protein
	else:
		stored.chain = []
		stored.resnam = []
		stored.resid = []
                cof_flag = []
		for na in cmd.get_names('objects'):
                    try:
                        if na == d_md_lig.object_name_prot:
                            cmd.select('pro', na)
                            cmd.select('pro2', 'pro and resn %s' % PDBcode_protein)
                            # check for co-factors
                            cf = 0
                            for pco, fco in zip(PDBcode_cofactors, filename_cofactors):
                                cmd.select('pro3', 'pro and resn %s' % pco)
                                if cmd.count_atoms('pro3') &gt; 0:
                                    cof_flag.append(cf)
                                cf += 1
                                cmd.delete('pro3')
                            cmd.select('pro4', 'pro and not resn %s' % PDBcode_protein_water)
                            L = cmd.count_atoms('pro4')
                            if L &gt; 0:
                                stored.list = []
                                cmd.iterate('pro4', 'stored.list.append((resi, resn))')
                                # remove duplicates
                                du = {}
                                for uu in stored.list:
                                    du[uu] = uu
                                fin_list = du.values()
                                fin_list.sort()
                                strg1 = ''
                                for sa, sb in fin_list:
                                    strg1 += '%s %s  ' % (sa, sb)
                                strg2 = 'The following residues are unknown by the force field: %s \n\n Please separate ligand into different object and/or define co-factors in folder %s' % (strg1, library_dir)    
                                
                                tkMessageBox.showwarning('Unknown residues', strg2)
                                cmd.delete('pro')
                                cmd.delete('pro2')
                                cmd.delete('pro4')
                                return 0
                            cmd.delete('pro4')
                    
                            L = cmd.count_atoms('pro2')
                            if L &gt; 0:
                                    rem = na
                                    find_disulfide_bridges('pro2') 
                                    cmd.select('sele2', 'pro and name CA+FE')
                                    cmd.iterate ('sele2', 'stored.chain.append(chain)')
                                    cmd.iterate ('sele2', 'stored.resnam.append(resn)')
                                    cmd.iterate ('sele2', 'stored.resid.append(resi)')
                                    cmd.save('prot_out.pdb','pro', 0, 'pdb')
                                    find_disulfide_bridges_2('prot_out.pdb', cof_flag, '000')
                                    # read first residue number in prot_out.pdb file for proper disulfide numbering
                                    for line in open('prot_out.pdb'):
                                        if line.find('ATOM') &gt;= 0:
                                            resid_zero = int(line[22:26].strip())
                                            break
                                    ResortPDB4Amber('prot_out.pdb') 
                            cmd.delete('pro')
                            cmd.delete('pro2')
                    except:
                        pass
        
# concatenate ligand and protein
		datalist = []
                datalist_SIE = []
		for line in open('NEWPDB.PDB'):
			datalist.append(line)
			datalist_SIE.append(line)
		datalist.append('TER\n')
		datalist_SIE.append('TER\n')
		for line in open('prot_out.pdb'):
                    if line[13:16] != 'H1 ' and line[13:16] != 'H2 ' and line[13:16] != 'H3 ' and line[13:16] != 'OXT':
			datalist.append(line)
                        if line[17:20] != 'WAT' and line[17:20] != 'HOH' and line[17:20] != 'SOL':
                            datalist_SIE.append(line)
		fout = open('prot_lig.pdb', 'w')
		fout.writelines(datalist)
		fout.close()
		fout = open('prot_lig_SIE.pdb', 'w')
		fout.writelines(datalist_SIE)
		fout.close()
                
                # write leapP.in
                # read first residue number in prot_out.pdb file for proper disulfide numbering
                for line in open('prot_lig.pdb'):
                    if line.find('ATOM') &gt;= 0:
                        resid_zero = int(line[22:26].strip())
                        break
		fout = open('leapP.in','w')
		fout.write('source leaprc.gaff\n')
		fout.write('source leaprc.ff03\n')
		fout.write('loadoff tmp.lib\n')
		fout.write('flig = loadamberparams tmp.frcmod\n')
                for j in cof_flag:
                    fout.write('loadoff %s.lib\n' % (filename_cofactors[j]))
                    fout.write('fcof = loadamberparams %s.frcmod\n' % (filename_cofactors[j]))
		fout.write('prot = loadpdb prot_lig.pdb\n')
                # add disulfide bridges
                for ds1_i, ds1_n, ds1_a, ds2_i, ds2_n, ds2_a in zip(disulfide_A, disulfide_A_name, disulfide_A_atom, disulfide_B, disulfide_B_name, disulfide_B_atom):
                    fout.write('bond prot.%d.%s prot.%d.%s\n' % (int(ds1_i)+resid_zero, ds1_a, int(ds2_i)+resid_zero, ds2_a))
		if wmd.solv_type == 'solv_cap':
			fout.write('solvateCap prot TIP3PBOX prot.%s %.2f\n' % (tmp_ligname, float(wmd.cap_radius)))
		elif wmd.solv_type == 'solv_box':
			fout.write('solvateBox prot TIP3PBOX %.2f\n' % (float(wmd.box_dim)))
			fout.write('addions prot Na+ 0\n')
			fout.write('addions prot Cl- 0\n')
		fout.write('saveoff prot prot.lib\n')
		fout.write('saveamberparm prot prot.top prot.trj\n')
		fout.write('quit\n')
		fout.close()
                
                # write leapP_SIE.in
                for line in open('prot_lig_SIE.pdb'):
                    if line.find('ATOM') &gt;= 0:
                        resid_zero = int(line[22:26].strip())
                        break
		fout = open('leapP_SIE.in','w')
		fout.write('source leaprc.gaff\n')
		fout.write('source leaprc.ff03\n')
		fout.write('loadoff tmp.lib\n')
		fout.write('flig = loadamberparams tmp.frcmod\n')
                for j in cof_flag:
                    fout.write('loadoff %s.lib\n' % (filename_cofactors[j]))
                    fout.write('fcof = loadamberparams %s.frcmod\n' % (filename_cofactors[j]))
		fout.write('prot = loadpdb prot_lig_SIE.pdb\n')
                # add disulfide bridges
                for ds1_i, ds1_n, ds1_a, ds2_i, ds2_n, ds2_a in zip(disulfide_A, disulfide_A_name, disulfide_A_atom, disulfide_B, disulfide_B_name, disulfide_B_atom):
                    fout.write('bond prot.%d.%s prot.%d.%s\n' % (int(ds1_i)+resid_zero, ds1_a, int(ds2_i)+resid_zero, ds2_a))
		fout.write('saveoff prot prot_SIE.lib\n')
		fout.write('saveamberparm prot prot_SIE.top prot_SIE.trj\n')
		fout.write('quit\n')
		fout.close()

	fmon = open('Monitor.prg', 'w')
        fmon.write('%s\n' % (md_program))
        fmon.write('%s\n' % (username))
        fmon.write('%s\n' % (wmd.computer_name))
        fmon.write('%d\n' % (wmd.ssh_port))
        fmon.write('%s\n' % (wmd.home_dir))
        fmon.write('%s\n' % (d_md_dir.project_dir_short))

        frun = open('RunScript', 'w')

        if md_program == 'amber':
            if wmd.local_or_server == 1:
                frun.write('#\n')
                frun.write('#PBS -l select=1:ncpus=%d:mpiprocs=%d,walltime=240:00:00\n' % (wmd.numnodes, wmd.numnodes))
                frun.write('#\n')
                frun.write('#\n')
                frun.write('cd $PBS_O_WORKDIR\n')
                frun.write('\n')
                frun.write('module load amber\n')
                frun.write('nohup mpirun -np %d %s/sander.MPI -O -i min.in -p prot.top -c prot.trj -o min.out -r min.rst -x min.trj -e min.edr -ref prot.trj\n' % (wmd.numnodes, wmd.amber_exe_dir))
            else:
                if wmd.numnodes == 1:
                    frun.write('nohup %s/sander -O -i min.in -p prot.top -c prot.trj -o min.out -r min.rst -x min.trj -e min.edr -ref prot.trj\n' % (wmd.amber_exe_dir))
                else:
                    frun.write('nohup mpirun -np %d %s/sander.MPI -O -i min.in -p prot.top -c prot.trj -o min.out -r min.rst -x min.trj -e min.edr -ref prot.trj\n' % (wmd.numnodes, wmd.amber_exe_dir))
            # write min.in
            if 1:
		fout = open('min.in','w')
		fout.write('initial minimisation\n')
		fout.write(' &amp;cntrl\n')
		fout.write('  imin   = 1,\n')
		tmpi = int(wmd.min_steps)
		fout.write('  maxcyc = %d,\n' % (tmpi))
		fout.write('  ncyc   = %d,\n' % (tmpi/2))
		fout.write('  ntx    = 1,\n')
		fout.write('  ntpr   = %d, ntwx	= %d, ntwe    = %d,\n' % (wmd.min_freqout, wmd.min_freqout, wmd.min_freqout))

		if wmd.solv_type == 'solv_cap':
			fout.write('  ntb  	 = 0,\n')
			fout.write('  ivcap	 = 0, fcap	= 5.0,\n')
			fout.write('  cut    = 12,\n')
		elif wmd.solv_type == 'solv_box':
			fout.write('  ntb  	 = 1,\n')
                        fout.write('  iwrap  = 1,\n')
		else:
			fout.write('  ntb  	 = 0,\n')
			fout.write('  igb    = 1,\n')
			fout.write('  cut    = 12,\n')

		if wmd.mintype == 'lig_p_fixed' or wmd.mintype == 'lig_p_zone':
			fout.write('  ntr    = 1, restraint_wt = 5.0,\n')
		if wmd.mintype == 'lig_p_fixed':
			fout.write('  restraintmask = \'(:1 &gt; :0.01)\',\n')
		if wmd.mintype == 'lig_p_zone':
			fout.write('  restraintmask = \'(:1 &gt;:%f)\',\n' % (wmd.zone_radius))

		fout.write(' /\n')
		fout.close()

		# generate pdb file for final structure
		frun.write('%s/ambpdb -p prot.top -aatm &lt; min.rst &gt; min_fin.pdb\n' % (wmd.amber_exe_dir))
                frun.write('touch min.done\n')

            if wmd.v_pr_yes.get() == 1:
		# write pr.in
		fout = open('pr.in','w')
		fout.write('equilibration, water only\n')
		fout.write(' &amp;cntrl\n')
		fout.write('  imin   = 0,\n')
		tmpi = int(wmd.pr_steps)
		fout.write('  nstlim = %d, dt	= %f,\n' % (tmpi, wmd.pr_timestep/1000.))
		fout.write('  ntc    = 2, ntf	= 2,\n') 
		fout.write('  ntx 	 = 1,\n')
		fout.write('  ntpr   = %d, ntwx	= %d, ntwe    = %d,\n' % (wmd.pr_freqout, wmd.pr_freqout, wmd.pr_freqout))

		if wmd.solv_type == 'solv_cap':
			fout.write('  ntb  	 = 0,\n')
			fout.write('  ivcap	 = 0, fcap	= 5.0,\n')
			fout.write('  cut    = 12,\n')
		elif wmd.solv_type == 'solv_box':
			fout.write('  ntb  	 = 1,\n')
                        fout.write('  iwrap  = 1,\n')
		else:
			fout.write('  ntb  	 = 0,\n')
                        fout.write('  nrespa = 2,\n')
			fout.write('  igb    = 1,\n')
			fout.write('  cut    = 12,\n')

		fout.write('  ntr    = 1, restraint_wt = 5.0,\n')
		if wmd.mintype == 'lig_p_fixed':
			fout.write('  restraintmask = \'(:1 &gt; :0.01) | !:WAT\',\n')
		elif wmd.mintype == 'lig_p_zone':
			fout.write('  restraintmask = \'(:1 &gt;:%f) | !:WAT\',\n' % (wmd.zone_radius))
		else: 
			fout.write('  restraintmask = \'!:WAT\',\n')

		fout.write('  ntt    = 3, temp0    = 300.0, gamma_ln    = 5.0,\n')

		fout.write(' /\n')
		fout.close()

                if wmd.local_or_server == 1:
                    frun.write('nohup mpirun -np %d %s/sander.MPI -O -i pr.in -p prot.top -c min.rst -o pr.out -r pr.rst -x pr.trj -e pr.edr -ref min.rst\n' % (wmd.numnodes, wmd.amber_exe_dir))
                else:
                    if wmd.numnodes == 1:
                        frun.write('nohup %s/sander -O -i pr.in -p prot.top -c min.rst -o pr.out -r pr.rst -x pr.trj -e pr.edr -ref min.rst\n' % (wmd.amber_exe_dir))
                    else:
                        frun.write('nohup mpirun -np %d %s/sander.MPI -O -i pr.in -p prot.top -c min.rst -o pr.out -r pr.rst -x pr.trj -e pr.edr -ref min.rst\n' % (wmd.numnodes, wmd.amber_exe_dir))
		# generate pdb file for final structure
		frun.write('%s/ambpdb -p prot.top -aatm &lt; pr.rst &gt; pr_fin.pdb\n' % (wmd.amber_exe_dir))
                # run analysis scripts
                # rmsd
                frun.write('%s/ptraj prot.top &lt;&lt; EOF\n' % (wmd.amber_exe_dir))
                frun.write('trajin min_fin.pdb\n')
                frun.write('trajin pr.trj\n')
                frun.write('strip :WAT\n')
                frun.write('strip \'@Cl-\'\n')
                frun.write('strip \'@Na+\'\n')
                frun.write('strip \'@H*\'\n')
                frun.write('rms first out pr_rmsd_allheavy.txt\n')
                frun.write('rms first out pr_rmsd_backbone.txt @CA,C,N\n')
                frun.write('EOF\n')

                frun.write('touch pr.done\n')

            if wmd.v_equ_yes.get() == 1:
		# write equ.in
		fout = open('equ.in','w')
		fout.write('equilibration\n')
		fout.write(' &amp;cntrl\n')
		fout.write('  imin   = 0,\n')
		tmpi = int(wmd.equ_steps)
		fout.write('  nstlim = %d, dt	= %f, nscm = 100,\n' % (tmpi, wmd.equ_timestep/1000.))
		fout.write('  ntc    = 2, ntf	= 2,\n') 
		fout.write('  ntx 	 = 7,\n')
		fout.write('  ntpr   = %d, ntwx	= %d, ntwe    = %d,\n' % (wmd.equ_freqout, wmd.equ_freqout, wmd.equ_freqout))

		if wmd.solv_type == 'solv_cap':
			fout.write('  ntb  	 = 0,\n')
                        fout.write('  nrespa = 2,\n')
			fout.write('  ivcap	 = 0, fcap	= 5.0,\n')
			fout.write('  cut    = 12,\n')
		elif wmd.solv_type == 'solv_box':
			fout.write('  ntb  	 = 1,\n')
                        fout.write('  iwrap  = 1,\n')
		else:
			fout.write('  ntb  	 = 0,\n')
                        fout.write('  nrespa = 2,\n')
			fout.write('  igb    = 1,\n')
			fout.write('  cut    = 12,\n')

		if wmd.mintype == 'lig_p_fixed' or wmd.mintype == 'lig_p_zone':
			fout.write('  ntr    = 1, restraint_wt = 5.0,\n')
		if wmd.mintype == 'lig_p_fixed':
			fout.write('  restraintmask = \'(:1 &gt; :0.01)\',\n')
		if wmd.mintype == 'lig_p_zone':
			fout.write('  restraintmask = \'(:1 &gt;:%f)\',\n' % (wmd.zone_radius))

		fout.write('  ntt    = 3, temp0    = 300.0, gamma_ln    = 5.0,\n')

		fout.write(' /\n')
		fout.close()

                if wmd.local_or_server == 1:
                    frun.write('nohup mpirun -np %d %s/sander.MPI -O -i equ.in -p prot.top -c pr.rst -o equ.out -r equ.rst -x equ.trj -e equ.edr -ref pr.rst\n' % (wmd.numnodes, wmd.amber_exe_dir))
                else:
                    if wmd.numnodes == 1:
                        frun.write('nohup %s/sander -O -i equ.in -p prot.top -c pr.rst -o equ.out -r equ.rst -x equ.trj -e equ.edr -ref pr.rst\n' % (wmd.amber_exe_dir))
                    else:
                        frun.write('nohup mpirun -np %d %s/sander.MPI -O -i equ.in -p prot.top -c pr.rst -o equ.out -r equ.rst -x equ.trj -e equ.edr -ref pr.rst\n' % (wmd.numnodes, wmd.amber_exe_dir))
		# generate pdb file for final structure
		frun.write('%s/ambpdb -p prot.top -aatm &lt; equ.rst &gt; equ_fin.pdb\n' % (wmd.amber_exe_dir))
                # run analysis scripts
                # rmsd
                frun.write('%s/ptraj prot.top &lt;&lt; EOF\n' % (wmd.amber_exe_dir))
                frun.write('trajin min_fin.pdb\n')
                frun.write('trajin equ.trj\n')
                frun.write('strip :WAT\n')
                frun.write('strip \'@Cl-\'\n')
                frun.write('strip \'@Na+\'\n')
                frun.write('strip \'@H*\'\n')
                frun.write('rms first out equ_rmsd_allheavy.txt\n')
                frun.write('rms first out equ_rmsd_backbone.txt @CA,C,N\n')
                frun.write('EOF\n')
                
                frun.write('touch equ.done\n')

            if wmd.v_md_yes.get() == 1:
		# write md.in
		fout = open('md.in','w')
		fout.write('production run\n')
		fout.write(' &amp;cntrl\n')
		fout.write('  imin   = 0,\n')
		tmpi = int(wmd.md_steps)
		fout.write('  nstlim = %d, dt	= %f, nscm = 100,\n' % (tmpi, wmd.md_timestep/1000.))
		fout.write('  ntc    = 2, ntf	= 2,\n') 
		fout.write('  ntx 	 = 7,\n')
		fout.write('  ntpr   = %d, ntwx	= %d, ntwe    = %d,\n' % (wmd.md_freqout, wmd.md_freqout, wmd.md_freqout))

		if wmd.solv_type == 'solv_cap':
			fout.write('  ntb  	 = 0,\n')
			fout.write('  ivcap	 = 0, fcap	= 5.0,\n')
			fout.write('  cut    = 12,\n')
		elif wmd.solv_type == 'solv_box':
			fout.write('  ntb  	 = 1,\n')
                        fout.write('  iwrap  = 1,\n')
		else:
			fout.write('  ntb  	 = 0,\n')
                        fout.write('  nrespa = 2,\n')
			fout.write('  igb    = 1,\n')
			fout.write('  cut    = 12,\n')

		if wmd.mintype == 'lig_p_fixed' or wmd.mintype == 'lig_p_zone':
			fout.write('  ntr    = 1, restraint_wt = 5.0,\n')
		if wmd.mintype == 'lig_p_fixed':
			fout.write('  restraintmask = \'(:1 &gt; :0.01)\',\n')
		if wmd.mintype == 'lig_p_zone':
			fout.write('  restraintmask = \'(:1 &gt;:%f)\',\n' % (wmd.zone_radius))

		fout.write('  ntt    = 3, temp0    = 300.0, gamma_ln    = 5.0,\n')

		fout.write(' /\n')
		fout.close()

                if wmd.local_or_server == 1:
                    frun.write('nohup mpirun -np %d %s/sander.MPI -O -i md.in -p prot.top -c equ.rst -o md.out -r md.rst -x md.trj -e md.edr -ref equ.rst\n' % (wmd.numnodes, wmd.amber_exe_dir))
                else:
                    if wmd.numnodes == 1:
                        frun.write('nohup %s/sander -O -i md.in -p prot.top -c equ.rst -o md.out -r md.rst -x md.trj -e md.edr -ref equ.rst\n' % (wmd.amber_exe_dir))
                    else:
                        frun.write('nohup mpirun -np %d %s/sander.MPI -O -i md.in -p prot.top -c equ.rst -o md.out -r md.rst -x md.trj -e md.edr -ref equ.rst\n' % (wmd.numnodes, wmd.amber_exe_dir))
		# generate pdb file for final structure
		frun.write('%s/ambpdb -p prot.top -aatm &lt; md.rst &gt; md_fin.pdb\n' % (wmd.amber_exe_dir))
                # run various analysis scripts
                # b-factor and rmsd
                frun.write('%s/ptraj prot.top &lt;&lt; EOF\n' % (wmd.amber_exe_dir))
                frun.write('trajin min_fin.pdb\n')
                frun.write('trajin md.trj\n')
                frun.write('strip :WAT\n')
                frun.write('strip \'@Cl-\'\n')
                frun.write('strip \'@Na+\'\n')
                frun.write('strip \'@H*\'\n')
                frun.write('rms first out md_rmsd_allheavy.txt\n')
                frun.write('rms first out md_rmsd_backbone.txt @CA,C,N\n')
                frun.write('atomicfluct out md_bfact_tmp.txt byatom bfactor\n')
                frun.write('atomicfluct out md_bfact.txt byres bfactor\n')
                frun.write('EOF\n')
#                frun.write('mv md_bfact_tmp.pdb.1 

                frun.write('%s/ptraj prot.top &lt;&lt; EOF\n' % (wmd.amber_exe_dir))
                frun.write('trajin min_fin.pdb\n')
                frun.write('strip :WAT\n')
                frun.write('strip \'@H*\'\n')
                frun.write('strip \'@Cl-\'\n')
                frun.write('strip \'@Na+\'\n')
                frun.write('trajout md_bfact_tmp.pdb pdb\n')
                frun.write('EOF\n')

                frun.write('touch md.done\n')

        # GROMACS
        else:
            frun.write('amb2gmx_ML.pl --prmtop prot.top --crd prot.trj --outname prot_min\n')
            frun.write('mv prot.top prot_amber.top\n')
            frun.write('mv prot_min.top prot.top\n')
            # write min.mdp
            if 1:
		fout = open('min.mdp','w')
		fout.write(';\n;energy minimization\n;\n;\n;\n')
                fout.write('title               = energy_minimization\n')
                fout.write('cpp                 = /usr/bin/cpp\n')
                fout.write('define              = -DFLEXIBLE\n')
                fout.write('constraints         = none\n')
                fout.write('integrator          = steep\n')
		tmpi = int(wmd.min_steps)
                fout.write('nsteps              = %d\n' % (tmpi))
                fout.write(';\n')
                fout.write('; Output specifications\n')
                fout.write(';\n')
                fout.write('nstlog             = %d\n' % (wmd.min_freqout))
                fout.write('nstxout             = %d\n' % (wmd.min_freqout))
                fout.write('nstenergy           = %d\n' % (wmd.min_freqout))
                fout.write('energygrps          = protein wat %s\n' % (tmp_ligname))
                fout.write(';\n')
                fout.write('; Force field specifications\n')
                fout.write(';\n')
                fout.write('nstlist             = 10\n')
                fout.write('ns_type             = grid\n')
                fout.write('rlist               = 1.0\n')
                fout.write('coulombtype         = PME\n')
                fout.write('rcoulomb            = 1.0\n')
                fout.write('rvdw                = 1.4\n')
                fout.write('vdwtype             = Cut-off\n')
                fout.write('fourierspacing      = 0.12\n')
                fout.write('fourier_nx          = 0\n')
                fout.write('fourier_ny          = 0\n')
                fout.write('fourier_nz          = 0\n')
                fout.write('pme_order           = 4\n')
                fout.write('ewald_rtol          = 1e-5\n')
                fout.write('optimize_fft        = yes\n')
                fout.write(';\n')
                fout.write('; Energy minimization specifications\n')
                fout.write(';\n')
                fout.write('emtol               = 1000.0\n')
                fout.write('emstep              = 0.01\n')
		fout.close()

                frun.write('grompp -f min.mdp -c prot_min.gro -p prot.top -o prot_min.tpr -np %d -maxwarn 50\n' % (wmd.num_proc))
		# generate pdb file for final structure
		frun.write('nohup mpirun -np %d mdrun -s prot_min.tpr -o prot_min.trr -c prot_pr.gro -g min.log -e min.edr\n' % (wmd.num_proc))
                frun.write('trjconv -f prot_min.trr -o prot_min.pdb -s prot_min.tpr &lt;&lt; 0\n')
                frun.write('touch min.done\n')

            if wmd.v_pr_yes.get() == 1:
		fout = open('pr.mdp','w')
                fout.write(';\n')
                fout.write('; position restraint\n')
                fout.write(';\n')
                fout.write(';\n')
                fout.write(';\n')
                fout.write('title		=  position_restraint\n')
                fout.write('cpp                 =  /usr/bin/cpp\n')
                fout.write('define              =  -DPOSRES\n')
                fout.write('constraints         =  hbonds\n')
                fout.write('lincs_order         =  8\n')
                fout.write('lincs_iter          =  5\n')
                fout.write('lincs_warnangle     =  40\n')
                fout.write('integrator          =  md\n')
		tmpi = int(wmd.pr_steps)
                fout.write('dt		        =  %f\n' % (wmd.pr_timestep/1000.))
                fout.write('nsteps              =  %d\n' % (tmpi))
                fout.write(';\n')
                fout.write('; Center-of-mass specifications\n')
                fout.write(';\n')
                fout.write('comm_mode   	= Angular\n')
                fout.write('comm_grps		= protein non-protein\n')
                fout.write('nstcomm		= 1\n')
                fout.write(';\n')
                fout.write('; Output specifications\n')
                fout.write(';\n')
                fout.write('nstxout             = %d\n' % (wmd.pr_freqout))
                fout.write('nstvout             = %d\n' % (wmd.pr_freqout))
                fout.write('nstfout             = 0\n')
                fout.write('nstlog              = %d\n' % (wmd.pr_freqout))
                fout.write('nstenergy           = %d\n' % (wmd.pr_freqout))
                fout.write('energygrps          = protein wat %s\n' % (tmp_ligname))
                fout.write(';\n')
                fout.write('; Force field specifications\n')
                fout.write(';\n')
                fout.write('nstlist             = 10\n')
                fout.write('ns_type             = grid\n')
                fout.write('rlist               = 1.0\n')
                fout.write('coulombtype         = PME\n')
                fout.write('rcoulomb            = 1.0\n')
                fout.write('rvdw                = 1.4\n')
                fout.write('vdwtype             = Cut-off\n')
                fout.write('fourierspacing      = 0.12\n')
                fout.write('fourier_nx          = 0\n')
                fout.write('fourier_ny          = 0\n')
                fout.write('fourier_nz          = 0\n')
                fout.write('pme_order           = 4\n')
                fout.write('ewald_rtol          = 1e-5\n')
                fout.write('optimize_fft        = yes\n')
                fout.write(';\n')
                fout.write('; Berendsen temperature coupling is on in four groups\n')
                fout.write('Tcoupl 		= berendsen\n')
                fout.write('tau_t 		= 0.1 	  0.1\n')
                fout.write('tc_grps 	        = protein non-protein\n')
                fout.write('ref_t 		= 300 	  300\n')
                fout.write(';\n')
                fout.write('; Pressure coupling is on\n')
                fout.write('Pcoupl 		= Parrinello-Rahman\n')
                fout.write('pcoupltype 	        = isotropic\n')
                fout.write('tau_p 		= 0.5\n')
                fout.write('compressibility     = 4.5e-5\n')
                fout.write('ref_p 		= 1.0\n')
                fout.write(';\n')
                fout.write('; Generate velocites is on at 300 K.\n')
                fout.write('gen_vel             = yes\n')
                fout.write('gen_temp            = 300.0\n')
                fout.write('gen_seed            = 123456\n')
		fout.close()

                frun.write('grompp -f pr.mdp -c prot_pr.gro -p prot.top -o prot_pr.tpr -np %d -maxwarn 50\n' % (wmd.num_proc))
		# generate pdb file for final structure
		frun.write('nohup mpirun -np %d mdrun -s prot_pr.tpr -o prot_pr.trr -c prot_equ.gro -g pr.log -e pr.edr\n' % (wmd.num_proc))
                frun.write('trjconv -f prot_pr.trr -o prot_pr.pdb -s prot_pr.tpr &lt;&lt; 0\n')
                frun.write('touch pr.done\n')

            if wmd.v_equ_yes.get() == 1:
		fout = open('equ.mdp','w')
                fout.write(';\n')
                fout.write('; equilibration\n')
                fout.write(';\n')
                fout.write(';\n')
                fout.write(';\n')
                fout.write('title		=  equilibration\n')
                fout.write('cpp                 =  /usr/bin/cpp\n')
                fout.write('constraints         =  hbonds\n')
                fout.write('lincs_order         =  8\n')
                fout.write('lincs_iter          =  5\n')
                fout.write('lincs_warnangle     =  40\n')
                fout.write('integrator          =  md\n')
		tmpi = int(wmd.equ_steps)
                fout.write('dt		        =  %f\n' % (wmd.equ_timestep/1000.))
                fout.write('nsteps              =  %d\n' % (tmpi))
                fout.write(';\n')
                fout.write('; Center-of-mass specifications\n')
                fout.write(';\n')
                fout.write('comm_mode   	= Angular\n')
                fout.write('comm_grps		= protein non-protein\n')
                fout.write('nstcomm		= 1\n')
                fout.write(';\n')
                fout.write('; Output specifications\n')
                fout.write(';\n')
                fout.write('nstxout             = %d\n' % (wmd.equ_freqout))
                fout.write('nstvout             = %d\n' % (wmd.equ_freqout))
                fout.write('nstfout             = 0\n')
                fout.write('nstlog              = %d\n' % (wmd.equ_freqout))
                fout.write('nstenergy           = %d\n' % (wmd.equ_freqout))
                fout.write('energygrps          = protein wat %s\n' % (tmp_ligname))
                fout.write(';\n')
                fout.write('; Force field specifications\n')
                fout.write(';\n')
                fout.write('nstlist             = 10\n')
                fout.write('ns_type             = grid\n')
                fout.write('rlist               = 1.0\n')
                fout.write('coulombtype         = PME\n')
                fout.write('rcoulomb            = 1.0\n')
                fout.write('rvdw                = 1.4\n')
                fout.write('vdwtype             = Cut-off\n')
                fout.write('fourierspacing      = 0.12\n')
                fout.write('fourier_nx          = 0\n')
                fout.write('fourier_ny          = 0\n')
                fout.write('fourier_nz          = 0\n')
                fout.write('pme_order           = 4\n')
                fout.write('ewald_rtol          = 1e-5\n')
                fout.write('optimize_fft        = yes\n')
                fout.write(';\n')
                fout.write('; Berendsen temperature coupling is on in four groups\n')
                fout.write('Tcoupl 		= nose-hoover\n')
                fout.write('tau_t 		= 0.1 	  0.1\n')
                fout.write('tc_grps 	        = protein non-protein\n')
                fout.write('ref_t 		= 300 	  300\n')
                fout.write(';\n')
                fout.write('; Pressure coupling is on\n')
                fout.write('Pcoupl 		= Parrinello-Rahman\n')
                fout.write('pcoupltype 	        = isotropic\n')
                fout.write('tau_p 		= 0.5\n')
                fout.write('compressibility     = 4.5e-5\n')
                fout.write('ref_p 		= 1.0\n')
                fout.write(';\n')
                fout.write('; Generate velocites is on at 300 K.\n')
                fout.write('gen_vel             = yes\n')
                fout.write('gen_temp            = 300.0\n')
                fout.write('gen_seed            = 123456\n')
		fout.close()

                frun.write('grompp -f equ.mdp -c prot_equ.gro -p prot.top -o prot_equ.tpr -np %d -maxwarn 50\n' % (wmd.num_proc))
		# generate pdb file for final structure
		frun.write('nohup mpirun -np %d mdrun -s prot_equ.tpr -o prot_equ.trr -c prot_md.gro -g equ.log -e equ.edr\n' % (wmd.num_proc))
                frun.write('trjconv -f prot_equ.trr -o prot_equ.pdb -s prot_equ.tpr &lt;&lt; 0\n')
                frun.write('touch equ.done\n')

            if wmd.v_md_yes.get() == 1:
		fout = open('md.mdp','w')
                fout.write(';\n')
                fout.write('; md\n')
                fout.write(';\n')
                fout.write(';\n')
                fout.write(';\n')
                fout.write('title		=  md\n')
                fout.write('cpp                 =  /usr/bin/cpp\n')
                fout.write('constraints         =  hbonds\n')
                fout.write('lincs_order         =  8\n')
                fout.write('lincs_iter          =  5\n')
                fout.write('lincs_warnangle     =  40\n')
                fout.write('integrator          =  md\n')
		tmpi = int(wmd.md_steps)
                fout.write('dt		        =  %f\n' % (wmd.md_timestep/1000.))
                fout.write('nsteps              =  %d\n' % (tmpi))
                fout.write(';\n')
                fout.write('; Center-of-mass specifications\n')
                fout.write(';\n')
                fout.write('comm_mode   	= Angular\n')
                fout.write('comm_grps		= protein non-protein\n')
                fout.write('nstcomm		= 1\n')
                fout.write(';\n')
                fout.write('; Output specifications\n')
                fout.write(';\n')
                fout.write('nstxout             = %d\n' % (wmd.md_freqout))
                fout.write('nstvout             = %d\n' % (wmd.md_freqout))
                fout.write('nstfout             = 0\n')
                fout.write('nstlog              = %d\n' % (wmd.md_freqout))
                fout.write('nstenergy           = %d\n' % (wmd.md_freqout))
                fout.write('energygrps          = protein wat %s\n' % (tmp_ligname))
                fout.write(';\n')
                fout.write('; Force field specifications\n')
                fout.write(';\n')
                fout.write('nstlist             = 10\n')
                fout.write('ns_type             = grid\n')
                fout.write('rlist               = 1.0\n')
                fout.write('coulombtype         = PME\n')
                fout.write('rcoulomb            = 1.0\n')
                fout.write('rvdw                = 1.4\n')
                fout.write('vdwtype             = Cut-off\n')
                fout.write('fourierspacing      = 0.12\n')
                fout.write('fourier_nx          = 0\n')
                fout.write('fourier_ny          = 0\n')
                fout.write('fourier_nz          = 0\n')
                fout.write('pme_order           = 4\n')
                fout.write('ewald_rtol          = 1e-5\n')
                fout.write('optimize_fft        = yes\n')
                fout.write(';\n')
                fout.write('; Berendsen temperature coupling is on in four groups\n')
                fout.write('Tcoupl 		= nose-hoover\n')
                fout.write('tau_t 		= 0.1 	  0.1\n')
                fout.write('tc_grps 	        = protein non-protein\n')
                fout.write('ref_t 		= 300 	  300\n')
                fout.write(';\n')
                fout.write('; Pressure coupling is on\n')
                fout.write('Pcoupl 		= Parrinello-Rahman\n')
                fout.write('pcoupltype 	        = isotropic\n')
                fout.write('tau_p 		= 0.5\n')
                fout.write('compressibility     = 4.5e-5\n')
                fout.write('ref_p 		= 1.0\n')
                fout.write(';\n')
                fout.write('; Generate velocites is on at 300 K.\n')
                fout.write('gen_vel             = yes\n')
                fout.write('gen_temp            = 300.0\n')
                fout.write('gen_seed            = 123456\n')
		fout.close()

                frun.write('grompp -f md.mdp -c prot_md.gro -p prot.top -o prot_md.tpr -np %d -maxwarn 50\n' % (wmd.num_proc))
		# generate pdb file for final structure
		frun.write('nohup mpirun -np %d mdrun -s prot_md.tpr -o prot_md.trr -c prot_fin.gro -g md.log -e md.edr\n' % (wmd.num_proc))
                frun.write('trjconv -f prot_md.trr -o prot_md.pdb -s prot_md.tpr &lt;&lt; 0\n')
                frun.write('touch md.done\n')

	frun.close()

	# run tleap on complex
        fcom = open('RunCommands', 'w')
        fcom.write('dos2unix prot_lig.pdb\n')
        fcom.write('dos2unix tmp.lib\n')
        fcom.write('dos2unix tmp.frcmod\n')
        fcom.write('dos2unix leapP.in\n')
        fcom.write('dos2unix leapP_SIE.in\n')
        fcom.write('dos2unix min.in\n')
        fcom.write('%s/exe/tleap -f leapP.in\n' % (amber_dir))
        fcom.write('%s/exe/tleap -f leapP_SIE.in\n' % (amber_dir))
        fcom.close()
        
#        os.system('mkdir %s' % (d_md_dir.project_dir_short))
        for j in cof_flag:
            os.system('cp %s/%s.lib %s/%s.frcmod ./tmp_amber/' % (library_dir, filename_cofactors[j], library_dir, filename_cofactors[j]))

        if md_program == 'amber': 
#            os.system('cp prot_lig.pdb prot_lig_SIE.pdb tmp.lib tmp.frcmod leap*.in RunCommands ./%s/' % (d_md_dir.project_dir_short))
            os.system('chmod u+rwx RunCommands; ./RunCommands')
#            os.system('cp ./%s/prot.top ./%s/prot.trj .' % (d_md_dir.project_dir_short, d_md_dir.project_dir_short, d_md_dir.project_dir_short, d_md_dir.project_dir_short))
        else:
#            os.system('cp prot_lig.pdb tmp.lib tmp.frcmod *.in *.mdp RunCommands RunScript ./%s/' % (d_md_dir.project_dir_short))
            os.system('chmod u+rwx RunCommands; ./RunCommands')
#            os.system('cp ./%s/*.mdp ./%s/RunScript ./%s/prot.top ./%s/prot_em.gro .' % (d_md_dir.project_dir_short, d_md_dir.project_dir_short, d_md_dir.project_dir_short, d_md_dir.project_dir_short))

	if os.path.exists('prot.top') == 0:
		tkMessageBox.showinfo('Problem in preparing MD simulation','Please check initial structure of protein-ligand complex.')
		return 0
        
        ftop = open('prot.top', 'r')

#        flag = 0
#        while ftop:
#            line = ftop.readline()
#            if flag == 1:
#                if line.find('WAT')  &gt; -1:
#                    j = line.find('WAT')
#                    break
#                elif line.find('Cl-')  &gt; -1:
#                    j = line.find('Cl-')
#                    break
#                elif line.find('Na+')  &gt; -1:
#                    j = line.find('Na+')
#                    break
#                else:
#                    ci += 1
#            if line.find('FLAG RESIDUE_LABEL') &gt; -1:
#                ftop.readline()
#                ci = 0
#                flag = 1
#        num_res = 20*ci + j/4
#        m = int(2*ci + j/40)
#        n = 2*j - int(j/40)*80
#
#        ftop.seek(0)
#        while ftop:
#            line = ftop.readline()
#            if line.find('FLAG RESIDUE_POINTER') &gt; -1:
#                ftop.readline()
#                cj = 0
#                while cj &lt;= m:
#                    line = ftop.readline()
#                    cj += 1
#                end_protein = int(line[n:n+8])-1
#                break


        ftop.seek(0)
        while ftop:
            line = ftop.readline()
            if line.find('FLAG RESIDUE_LABEL') &gt; -1:
                ftop.readline()
                flag_wat = 0
                ci = 0
                while flag_wat == 0:
                    line = ftop.readline()
                    if line.find('Cl-') &gt;= 0:
                        a = line.find('Cl-')
                        b = a/4-1
                        num = 20*ci + b
                        flag_wat = 1
                    elif line.find('Na+') &gt;= 0:
                        a = line.find('Na+')
                        b = a/4-1
                        num = 20*ci + b
                        flag_wat = 1
                    elif line.find('WAT') &gt;= 0:
                        a = line.find('WAT')
                        b = a/4-1
                        num = 20*ci + b
                        flag_wat = 1
                    else:
                        ci += 1
                break


#        print '%d %d %d' % (num, ci, b)
        
#        ftop.seek(0)
#        while ftop:
#            line = ftop.readline()
#            if line.find('FLAG POINTERS') &gt; -1:
#                ftop.readline()
#                line = ftop.readline()
#                break
#        end_protein = int(line[0:8])

        
        ftop.seek(0)
        while ftop:
            line = ftop.readline()
            if line.find('FLAG RESIDUE_POINTER') &gt; -1:
                ftop.readline()
                line = ftop.readline()
                break
        # ligand is first entry
        start_lig_id = int(line[0:8])
        end_lig_id = int(line[8:16])-1
        # end of protein: ((num+1 residue) - 1)
        if num &lt; 9:
            sa = num*8
            sb = (num+1)*8
            end_protein = int(line[sa:sb])-1
        else:
            nline = ci*2
            if b == 19:
                nline += 2
                sa = 0
            elif b == 9:
                nline += 1
                sa = 0
            elif b &gt; 9:
                nline += 1
                sa = (b-9)*8
            else:
                sa = b*8
            sb = sa + 8
            for k in range(nline-1):
                line = ftop.readline()
            line = ftop.readline()
            end_protein = int(line[sa:sb])-1
                


#        print '%d : %d %d : %d' % (nline, sa, sb, end_protein)
        
        ftop.close()

        fmon.write('%d %d %d %d\n' % (end_lig_id+1, end_protein, start_lig_id, end_lig_id))
        fmon.close()
#        return 0


        # copy files for actual simulation
        if md_program == 'amber': 
            if wmd.local_or_server == 0:
                os.system('mkdir %s' % (d_md_dir.project_dir_short))
                os.system('cp prot.top prot.trj *.in RunScript ./%s/' % (d_md_dir.project_dir_short))
            else:
                os.system("ssh -p %d %s@%s 'cd %s; mkdir %s'" % (wmd.ssh_port, username, wmd.computer_name, wmd.home_dir, d_md_dir.project_dir_short))
                os.system('scp -P %d prot.top prot.trj *.in RunScript %s@%s:%s/%s/' % (wmd.ssh_port, username, wmd.computer_name, wmd.home_dir, d_md_dir.project_dir_short))
        else:
            pass



        if wmd.run_settings == 'prep':
            if wmd.local_or_server == 0:
                childp = subprocess.Popen('cd ./%s; chmod u+rwx RunScript' % (d_md_dir.project_dir_short), shell=True)
                tkMessageBox.showinfo('Preparation of MM calculation done',"Please enter folder %s_client/%s and start job by typing 'nohup ./RunScript &amp;'.\nData can be read in by using 'Amber, Monitor molecular mechanics results'." % (d_md_dir.project_dir, d_md_dir.project_dir))
            else:
                childp = subprocess.Popen("ssh -p %d %s@%s 'cd %s/%s; chmod u+rwx RunScript'" % (wmd.ssh_port, username, wmd.computer_name, wmd.home_dir, d_md_dir.project_dir_short), shell=True)
                tkMessageBox.showinfo('Preparation of MM calculation done',"Please copy folder %s_client/%s to server and start job by typing 'nohup ./RunScript &amp;'.\nData can be read in by using 'Amber, Monitor molecular mechanics results'." % (d_md_dir.project_dir, d_md_dir.project_dir))
        else:
            if wmd.local_or_server == 0:
                childp = subprocess.Popen('cd ./%s; chmod u+rwx RunScript; nohup ./RunScript &amp;' % (d_md_dir.project_dir_short), shell=True)
                tkMessageBox.showinfo('Preparation of MM calculation done',"Job has been started on localhost.\nData can be read in by using 'Amber, Monitor molecular mechanics results'.")
            else:
                childp = subprocess.Popen("ssh -p %d %s@%s 'cd %s/%s; chmod u+rwx RunScript; /usr/pbs/bin/qsub -q %s RunScript'" % (wmd.ssh_port, username, wmd.computer_name, wmd.home_dir, d_md_dir.project_dir_short, wmd.queue_name), shell=True)
                tkMessageBox.showinfo('Preparation of MM calculation done',"Job has been started on server.\nData can be read in by using 'Amber, Monitor molecular mechanics results'.")
   


        if md_program == 'amber':
#            if wmd.v_min_yes.get() == 1:
#                os.remove('min.in') 
#            if wmd.v_pr_yes.get() == 1:
#                os.remove('pr.in') 
#            if wmd.v_equ_yes.get() == 1:
#                os.remove('equ.in') 
#            if wmd.v_md_yes.get() == 1:
#                os.remove('md.in') 
            os.remove('leapL.in') 
            os.remove('leapP.in') 
            try:
                os.remove('prot.top')
            except:
                pass
                
            try:
                os.remove('prot.trj')
            except:
                pass
                
            try:
                os.remove('NEWPDB.PDB')
            except:
                pass
                
            try:
                os.remove('prot_lig.pdb')
            except:
                pass
                
            try:
                os.remove('prot_out.pdb')
            except:
                pass
                
            try:
                os.remove('RunCommands')
            except:
                pass
                
            try:
                os.remove('RunScript')
            except:
                pass
                
            try:
                shutil.move('tmp.frcmod', '%s.frcmod' % tmp_ligname)
            except:
                pass
                
            try:
                shutil.move('tmp.lib', '%s.lib' % tmp_ligname)
            except:
                pass
                
            try:
                os.remove('tmp.mol2')
            except:
                pass
                
            try:
                os.remove('tmp.prepin')
            except:
                pass
                

#        os.chmod('RunScript', S_IRWXU)
#	os.system('chmod a+x RunScript') 
     
#	os.system('rm tmp.*')

	os.chdir(curdir)

	print('preparation for md simulation done')

#######################################################################################
def md_simulation_protein(app, md_program):
        global com_x
        global com_y
        global com_z

        # find number of object in list
        object_list = []
        for na in cmd.get_names('objects'):
            try:
                object_list.append(na)
            except:
                pass

        # select protein object
	d_md_lig = minimProt_dialog(app.root)
	if d_md_lig.ok_flag == 0:
		return 0

        # calculate COM
	for na in cmd.get_names('objects'):
            try:
                if na == d_md_lig.object_name_prot:
                    cmd.select('pro', na)
                    cmd.select('pro2', 'pro and resn ALA+ARG+ASH+ASN+ASP+CYS+CYX+CY1+GLH+GLN+GLU+GLY+HIS+HIE+HID+HIP+ILE+LEU+LYS+MET+PHE+PRO+SER+THR+TRP+TYR+VAL+HEM+HEO+FAD')
                    # define center of protein
                    model = cmd.get_model('pro2')
                    x, y, z = 0,0,0
                    min_x, min_y, min_z = 99999,99999,99999
                    max_x, max_y, max_z = -99999,-99999,-99999
                    for a in model.atom:
                        x += a.coord[0]
                        y += a.coord[1]
                        z += a.coord[2]
                        if a.coord[0] &lt; min_x:
                            min_x = a.coord[0]
                        if a.coord[0] &gt; max_x:
                            max_x = a.coord[0]
                        if a.coord[1] &lt; min_y:
                            min_y = a.coord[1]
                        if a.coord[1] &gt; max_y:
                            max_y = a.coord[1]
                        if a.coord[2] &lt; min_z:
                            min_z = a.coord[2]
                        if a.coord[2] &gt; max_z:
                            max_z = a.coord[2]
                    com_x = x/len(model.atom)
                    com_y = y/len(model.atom)
                    com_z = z/len(model.atom)
                    cmd.delete('pro')
                    cmd.delete('pro2')
                    
            except:
                pass

        # select directory for project
        d_md_dir = saveDialog(app.root)
	if d_md_dir.ok_flag == 0:
		return

	md_outfile = d_md_dir.project_dir + '_client'
	md_save_project = 1

        # create project directory and delete old files (if existing)
	if os.path.isdir(md_outfile):
            for af in os.listdir(md_outfile):
                possible_dir = md_outfile + '/%s' % (af)
#                print 'aaa %s %s' % (af, possible_dir)
                if os.path.isdir(possible_dir):
#                    print 'bbb %s' % (af)
                    for bf in os.listdir(possible_dir):
                        os.remove('%s/%s' % (possible_dir, bf))
                    os.rmdir(possible_dir)
                else:
#                    print 'ccc %s' % (af)
                    os.remove('%s/%s' % (md_outfile, af))
            os.rmdir(md_outfile)
        os.mkdir(md_outfile)

	curdir = os.getcwd()

        # change into project directory
        os.chdir(md_outfile)






        # specify MM settings
        if md_program == 'amber':
            wmd = mdsimulationDialog_protein(app.root)
        else:
            wmd = mdsimulationDialog_gromacs(app.root)

	if wmd.ok_flag == 0:
		return 0
                
        
	# generate leapP.in file
	stored.chain = []
	stored.resnam = []
	stored.resid = []
        cof_flag = []
	for na in cmd.get_names('objects'):
            try:
                if na == d_md_lig.object_name_prot:
                    cmd.select('pro', na)
                    cmd.select('pro2', 'pro and resn %s' % PDBcode_protein)
                    # check for co-factors
                    cf = 0
                    for pco, fco in zip(PDBcode_cofactors, filename_cofactors):
                        cmd.select('pro3', 'pro and resn %s' % pco)
                        if cmd.count_atoms('pro3') &gt; 0:
                            cof_flag.append(cf)
                        cf += 1
                        cmd.delete('pro3')
                    cmd.select('pro4', 'pro and not resn %s' % PDBcode_protein_water)
                    L = cmd.count_atoms('pro4')
                    if L &gt; 0:
                        stored.list = []
                        cmd.iterate('pro4', 'stored.list.append((resi, resn))')
                        # remove duplicates
                        du = {}
                        for uu in stored.list:
                            du[uu] = uu
                        fin_list = du.values()
                        fin_list.sort()
                        strg1 = ''
                        for sa, sb in fin_list:
                            strg1 += '%s %s  ' % (sa, sb)
                        strg2 = 'The following residues are unknown by the force field: %s \n\n Please separate ligand into different object and/or define co-factors in folder %s' % (strg1, library_dir)    
                        
                        tkMessageBox.showwarning('Unknown residues', strg2)
                        cmd.delete('pro')
                        cmd.delete('pro2')
                        cmd.delete('pro4')
                        return 0
                    cmd.delete('pro4')
            
                    L = cmd.count_atoms('pro2')
                    if L &gt; 0:
                            rem = na
                            find_disulfide_bridges('pro2') 
                            cmd.select('sele2', 'pro and name CA+FE')
                            cmd.iterate ('sele2', 'stored.chain.append(chain)')
                            cmd.iterate ('sele2', 'stored.resnam.append(resn)')
                            cmd.iterate ('sele2', 'stored.resid.append(resi)')
                            cmd.save('prot_out.pdb','pro', 0, 'pdb')
                            find_disulfide_bridges_2('prot_out.pdb', cof_flag, '000')
                            # read first residue number in prot_out.pdb file for proper disulfide numbering
                            for line in open('prot_out.pdb'):
                                if line.find('ATOM') &gt;= 0:
                                    resid_zero = int(line[22:26].strip())
                                    break
                            ResortPDB4Amber('prot_out.pdb') 
                    cmd.delete('pro')
                    cmd.delete('pro2')
            except:
                pass
        
# protein
	datalist = []
	for line in open('prot_out.pdb'):
            if line[13:16] != 'H1 ' and line[13:16] != 'H2 ' and line[13:16] != 'H3 ' and line[13:16] != 'OXT':
		datalist.append(line)

        # add dummy atom for cap simulation
        if wmd.solv_type == 'solv_cap':
            datalist.append('ATOM   9999  DD  DDD   999    % 8.3f% 8.3f% 8.3f\n' % (wmd.sphere_center_x, wmd.sphere_center_y, wmd.sphere_center_z))
            ffrcmod = open('DDD.frcmod', 'w')
            ffrcmod.write('Dummy atoms for cap simulation\n')
            ffrcmod.write('MASS\n')
            ffrcmod.write('DD     1.00     0.00        \n')
            ffrcmod.write('\n')
            ffrcmod.write('NONB\n')
            ffrcmod.write('  DD        0.1000     0.0000\n')
            ffrcmod.close()
            flib = open('DDD.lib', 'w')
            flib.write('!!index array str\n')
            flib.write(' \'DDD\'\n')
            flib.write('!entry.DDD.unit.atoms table  str name  str type  int typex  int resx  int flags  int seq  int elmnt  dbl chg\n')
            flib.write(' \'DD\' \'DD\' 0 1 131072 1 -1 0.0\n')
            flib.write('!entry.DDD.unit.atomspertinfo table  str pname  str ptype  int ptypex  int pelmnt  dbl pchg\n')
            flib.write(' \'DD\' \'DD\' 0 -1 0.0\n')
            flib.write('!entry.DDD.unit.boundbox array dbl\n')
            flib.write(' -1.000000\n')
            flib.write(' 0.0\n')
            flib.write(' 0.0\n')
            flib.write(' 0.0\n')
            flib.write(' 0.0\n')
            flib.write('!entry.DDD.unit.childsequence single int\n')
            flib.write(' 999\n')
            flib.write('!entry.DDD.unit.connect array int\n')
            flib.write(' 0\n')
            flib.write(' 0\n')
            flib.write('!entry.DDD.unit.hierarchy table  str abovetype  int abovex  str belowtype  int belowx\n')
            flib.write(' \'U\' 0 \'R\' 1\n')
            flib.write(' \'R\' 1 \'A\' 1\n')
            flib.write('!entry.DDD.unit.name single str\n')
            flib.write(' \'\'\n')
            flib.write('!entry.DDD.unit.positions table  dbl x  dbl y  dbl z\n')
            flib.write(' 0.002722 2.070234 0.003730\n')
            flib.write('!entry.DDD.unit.residueconnect table  int c1x  int c2x  int c3x  int c4x  int c5x  int c6x\n')
            flib.write(' 0 0 0 0 0 0\n')
            flib.write('!entry.DDD.unit.residues table  str name  int seq  int childseq  int startatomx  str restype  int imagingx\n')
            flib.write(' \'DDD\' 998 2 1 \'?\' 0\n')
            flib.write('!entry.DDD.unit.residuesPdbSequenceNumber array int\n')
            flib.write(' 1\n')
            flib.write('!entry.CO6.unit.solventcap array dbl\n')
            flib.write(' -1.000000\n')
            flib.write(' 0.0\n')
            flib.write(' 0.0\n')
            flib.write(' 0.0\n')
            flib.write(' 0.0\n')
            flib.write('!entry.CO6.unit.velocities table  dbl x  dbl y  dbl z\n')
            flib.write(' 0.0 0.0 0.0\n')
            flib.close()


	fout = open('prot_lig.pdb', 'w')
	fout.writelines(datalist)
	fout.close()
        
        # write leapP.in
        # read first residue number in prot_out.pdb file for proper disulfide numbering
        for line in open('prot_lig.pdb'):
            if line.find('ATOM') &gt;= 0:
                resid_zero = int(line[22:26].strip())
                break
	fout = open('leapP.in','w')
	fout.write('source leaprc.gaff\n')
	fout.write('source leaprc.ff03\n')
        for j in cof_flag:
            fout.write('loadoff %s.lib\n' % (filename_cofactors[j]))
            fout.write('fcof = loadamberparams %s.frcmod\n' % (filename_cofactors[j]))
        if wmd.solv_type == 'solv_cap':
            fout.write('loadoff DDD.lib\n')
            fout.write('ffad = loadamberparams DDD.frcmod\n')
	fout.write('prot = loadpdb prot_lig.pdb\n')
        # add disulfide bridges
        for ds1_i, ds1_n, ds1_a, ds2_i, ds2_n, ds2_a in zip(disulfide_A, disulfide_A_name, disulfide_A_atom, disulfide_B, disulfide_B_name, disulfide_B_atom):
            fout.write('bond prot.%d.%s prot.%d.%s\n' % (int(ds1_i)+resid_zero-1, ds1_a, int(ds2_i)+resid_zero-1, ds2_a))
	if wmd.solv_type == 'solv_cap':
		fout.write('solvateCap prot TIP3PBOX {%.2f %.2f %.2f} %.2f\n' % (wmd.sphere_center_x, wmd.sphere_center_y, wmd.sphere_center_z, float(wmd.cap_radius)))
	elif wmd.solv_type == 'solv_box':
		fout.write('solvateBox prot TIP3PBOX %.2f\n' % (float(wmd.box_dim)))
		fout.write('addions prot Na+ 0\n')
		fout.write('addions prot Cl- 0\n')
	fout.write('saveoff prot prot.lib\n')
	fout.write('saveamberparm prot prot.top prot.trj\n')
	fout.write('quit\n')
	fout.close()
        
	fmon = open('Monitor.prg', 'w')
        fmon.write('%s\n' % (md_program))
        fmon.write('%s\n' % (username))
        fmon.write('%s\n' % (wmd.computer_name))
        fmon.write('%d\n' % (wmd.ssh_port))
        fmon.write('%s\n' % (wmd.home_dir))
        fmon.write('%s\n' % (d_md_dir.project_dir_short))

        frun = open('RunScript', 'w')

        if md_program == 'amber':
            if wmd.local_or_server == 1:
                frun.write('#\n')
                frun.write('#PBS -l select=1:ncpus=%d:mpiprocs=%d,walltime=240:00:00\n' % (wmd.numnodes, wmd.numnodes))
                frun.write('#\n')
                frun.write('#\n')
                frun.write('cd $PBS_O_WORKDIR\n')
                frun.write('\n')
                frun.write('module load amber\n')
                frun.write('nohup mpirun -np %d %s/sander.MPI -O -i min.in -p prot.top -c prot.trj -o min.out -r min.rst -x min.trj -e min.edr -ref prot.trj\n' % (wmd.numnodes, wmd.amber_exe_dir))
            else:
                if wmd.numnodes == 1:
                    frun.write('nohup %s/sander -O -i min.in -p prot.top -c prot.trj -o min.out -r min.rst -x min.trj -e min.edr -ref prot.trj\n' % (wmd.amber_exe_dir))
                else:
                    frun.write('nohup mpirun -np %d %s/sander.MPI -O -i min.in -p prot.top -c prot.trj -o min.out -r min.rst -x min.trj -e min.edr -ref prot.trj\n' % (wmd.numnodes, wmd.amber_exe_dir))
            # write min.in
            if 1:
		fout = open('min.in','w')
		fout.write('initial minimisation\n')
		fout.write(' &amp;cntrl\n')
		fout.write('  imin   = 1,\n')
		tmpi = int(wmd.min_steps)
		fout.write('  maxcyc = %d,\n' % (tmpi))
		fout.write('  ncyc   = %d,\n' % (tmpi/2))
		fout.write('  ntx    = 1,\n')
		fout.write('  ntpr   = %d, ntwx	= %d, ntwe    = %d,\n' % (wmd.min_freqout, wmd.min_freqout, wmd.min_freqout))

		if wmd.solv_type == 'solv_cap':
			fout.write('  ntb  	 = 0,\n')
			fout.write('  ivcap	 = 0, fcap	= 5.0,\n')
			fout.write('  cut    = 12,\n')
		elif wmd.solv_type == 'solv_box':
			fout.write('  ntb  	 = 1,\n')
                        fout.write('  iwrap  = 1,\n')
		else:
			fout.write('  ntb  	 = 0,\n')
			fout.write('  igb    = 1,\n')
			fout.write('  cut    = 12,\n')

		if wmd.mintype == 'lig_p_zone':
			fout.write('  ntr    = 1, restraint_wt = 5.0,\n')
			fout.write('  restraintmask = \'(:DDD &gt;:%f) | :DDD\',\n' % (wmd.zone_radius))

		fout.write(' /\n')
		fout.close()

		# generate pdb file for final structure
		frun.write('%s/ambpdb -p prot.top -aatm &lt; min.rst &gt; min_fin.pdb\n' % (wmd.amber_exe_dir))
                frun.write('touch min.done\n')

            if wmd.v_pr_yes.get() == 1:
		# write pr.in
		fout = open('pr.in','w')
		fout.write('equilibration, water only\n')
		fout.write(' &amp;cntrl\n')
		fout.write('  imin   = 0,\n')
		tmpi = int(wmd.pr_steps)
		fout.write('  nstlim = %d, dt	= %f,\n' % (tmpi, wmd.pr_timestep/1000.))
		fout.write('  ntc    = 2, ntf	= 2,\n') 
		fout.write('  ntx 	 = 1,\n')
		fout.write('  ntpr   = %d, ntwx	= %d, ntwe    = %d,\n' % (wmd.pr_freqout, wmd.pr_freqout, wmd.pr_freqout))

		if wmd.solv_type == 'solv_cap':
			fout.write('  ntb  	 = 0,\n')
			fout.write('  ivcap	 = 0, fcap	= 5.0,\n')
			fout.write('  cut    = 12,\n')
		elif wmd.solv_type == 'solv_box':
			fout.write('  ntb  	 = 1,\n')
                        fout.write('  iwrap  = 1,\n')
		else:
			fout.write('  ntb  	 = 0,\n')
                        fout.write('  nrespa = 2,\n')
			fout.write('  igb    = 1,\n')
			fout.write('  cut    = 12,\n')

		fout.write('  ntr    = 1, restraint_wt = 5.0,\n')
                if wmd.mintype == 'lig_p_zone':
			fout.write('  restraintmask = \'(:DDD &gt;:%f) | :DDD | !:WAT\',\n' % (wmd.zone_radius))
		else: 
			fout.write('  restraintmask = \'!:WAT\',\n')

		fout.write('  ntt    = 3, temp0    = 300.0, gamma_ln    = 5.0,\n')

		fout.write(' /\n')
		fout.close()

                if wmd.local_or_server == 1:
                    frun.write('nohup mpirun -np %d %s/sander.MPI -O -i pr.in -p prot.top -c min.rst -o pr.out -r pr.rst -x pr.trj -e pr.edr -ref min.rst\n' % (wmd.numnodes, wmd.amber_exe_dir))
                else:
                    if wmd.numnodes == 1:
                        frun.write('nohup %s/sander -O -i pr.in -p prot.top -c min.rst -o pr.out -r pr.rst -x pr.trj -e pr.edr -ref min.rst\n' % (wmd.amber_exe_dir))
                    else:
                        frun.write('nohup mpirun -np %d %s/sander.MPI -O -i pr.in -p prot.top -c min.rst -o pr.out -r pr.rst -x pr.trj -e pr.edr -ref min.rst\n' % (wmd.numnodes, wmd.amber_exe_dir))
		# generate pdb file for final structure
		frun.write('%s/ambpdb -p prot.top -aatm &lt; pr.rst &gt; pr_fin.pdb\n' % (wmd.amber_exe_dir))
                # run analysis scripts
                # rmsd
                frun.write('%s/ptraj prot.top &lt;&lt; EOF\n' % (wmd.amber_exe_dir))
                frun.write('trajin min_fin.pdb\n')
                frun.write('trajin pr.trj\n')
                frun.write('strip :WAT\n')
                frun.write('strip \'@Cl-\'\n')
                frun.write('strip \'@Na+\'\n')
                frun.write('strip \'@H*\'\n')
                frun.write('rms first out pr_rmsd_allheavy.txt\n')
                frun.write('rms first out pr_rmsd_backbone.txt @CA,C,N\n')
                frun.write('EOF\n')

                frun.write('touch pr.done\n')

            if wmd.v_equ_yes.get() == 1:
		# write equ.in
		fout = open('equ.in','w')
		fout.write('equilibration\n')
		fout.write(' &amp;cntrl\n')
		fout.write('  imin   = 0,\n')
		tmpi = int(wmd.equ_steps)
		fout.write('  nstlim = %d, dt	= %f, nscm = 100,\n' % (tmpi, wmd.equ_timestep/1000.))
		fout.write('  ntc    = 2, ntf	= 2,\n') 
		fout.write('  ntx 	 = 7,\n')
		fout.write('  ntpr   = %d, ntwx	= %d, ntwe    = %d,\n' % (wmd.equ_freqout, wmd.equ_freqout, wmd.equ_freqout))

		if wmd.solv_type == 'solv_cap':
			fout.write('  ntb  	 = 0,\n')
                        fout.write('  nrespa = 2,\n')
			fout.write('  ivcap	 = 0, fcap	= 5.0,\n')
			fout.write('  cut    = 12,\n')
		elif wmd.solv_type == 'solv_box':
			fout.write('  ntb  	 = 1,\n')
                        fout.write('  iwrap  = 1,\n')
		else:
			fout.write('  ntb  	 = 0,\n')
                        fout.write('  nrespa = 2,\n')
			fout.write('  igb    = 1,\n')
			fout.write('  cut    = 12,\n')

                if wmd.mintype == 'lig_p_zone':
			fout.write('  ntr    = 1, restraint_wt = 5.0,\n')
			fout.write('  restraintmask = \'(:DDD &gt;:%f) | :DDD | !:WAT\',\n' % (wmd.zone_radius))

		fout.write('  ntt    = 3, temp0    = 300.0, gamma_ln    = 5.0,\n')

		fout.write(' /\n')
		fout.close()

                if wmd.local_or_server == 1:
                    frun.write('nohup mpirun -np %d %s/sander.MPI -O -i equ.in -p prot.top -c pr.rst -o equ.out -r equ.rst -x equ.trj -e equ.edr -ref pr.rst\n' % (wmd.numnodes, wmd.amber_exe_dir))
                else:
                    if wmd.numnodes == 1:
                        frun.write('nohup %s/sander -O -i equ.in -p prot.top -c pr.rst -o equ.out -r equ.rst -x equ.trj -e equ.edr -ref pr.rst\n' % (wmd.amber_exe_dir))
                    else:
                        frun.write('nohup mpirun -np %d %s/sander.MPI -O -i equ.in -p prot.top -c pr.rst -o equ.out -r equ.rst -x equ.trj -e equ.edr -ref pr.rst\n' % (wmd.numnodes, wmd.amber_exe_dir))
		# generate pdb file for final structure
		frun.write('%s/ambpdb -p prot.top -aatm &lt; equ.rst &gt; equ_fin.pdb\n' % (wmd.amber_exe_dir))
                # run analysis scripts
                # rmsd
                frun.write('%s/ptraj prot.top &lt;&lt; EOF\n' % (wmd.amber_exe_dir))
                frun.write('trajin min_fin.pdb\n')
                frun.write('trajin equ.trj\n')
                frun.write('strip :WAT\n')
                frun.write('strip \'@Cl-\'\n')
                frun.write('strip \'@Na+\'\n')
                frun.write('strip \'@H*\'\n')
                frun.write('rms first out equ_rmsd_allheavy.txt\n')
                frun.write('rms first out equ_rmsd_backbone.txt @CA,C,N\n')
                frun.write('EOF\n')
                
                frun.write('touch equ.done\n')

            if wmd.v_md_yes.get() == 1:
		# write md.in
		fout = open('md.in','w')
		fout.write('production run\n')
		fout.write(' &amp;cntrl\n')
		fout.write('  imin   = 0,\n')
		tmpi = int(wmd.md_steps)
		fout.write('  nstlim = %d, dt	= %f, nscm = 100,\n' % (tmpi, wmd.md_timestep/1000.))
		fout.write('  ntc    = 2, ntf	= 2,\n') 
		fout.write('  ntx 	 = 7,\n')
		fout.write('  ntpr   = %d, ntwx	= %d, ntwe    = %d,\n' % (wmd.md_freqout, wmd.md_freqout, wmd.md_freqout))

		if wmd.solv_type == 'solv_cap':
			fout.write('  ntb  	 = 0,\n')
			fout.write('  ivcap	 = 0, fcap	= 5.0,\n')
			fout.write('  cut    = 12,\n')
		elif wmd.solv_type == 'solv_box':
			fout.write('  ntb  	 = 1,\n')
                        fout.write('  iwrap  = 1,\n')
		else:
			fout.write('  ntb  	 = 0,\n')
                        fout.write('  nrespa = 2,\n')
			fout.write('  igb    = 1,\n')
			fout.write('  cut    = 12,\n')

                if wmd.mintype == 'lig_p_zone':
			fout.write('  ntr    = 1, restraint_wt = 5.0,\n')
			fout.write('  restraintmask = \'(:DDD &gt;:%f) | :DDD | !:WAT\',\n' % (wmd.zone_radius))

		fout.write('  ntt    = 3, temp0    = 300.0, gamma_ln    = 5.0,\n')

		fout.write(' /\n')
		fout.close()

                if wmd.local_or_server == 1:
                    frun.write('nohup mpirun -np %d %s/sander.MPI -O -i md.in -p prot.top -c equ.rst -o md.out -r md.rst -x md.trj -e md.edr -ref equ.rst\n' % (wmd.numnodes, wmd.amber_exe_dir))
                else:
                    if wmd.numnodes == 1:
                        frun.write('nohup %s/sander -O -i md.in -p prot.top -c equ.rst -o md.out -r md.rst -x md.trj -e md.edr -ref equ.rst\n' % (wmd.amber_exe_dir))
                    else:
                        frun.write('nohup mpirun -np %d %s/sander.MPI -O -i md.in -p prot.top -c equ.rst -o md.out -r md.rst -x md.trj -e md.edr -ref equ.rst\n' % (wmd.numnodes, wmd.amber_exe_dir))
		# generate pdb file for final structure
		frun.write('%s/ambpdb -p prot.top -aatm &lt; md.rst &gt; md_fin.pdb\n' % (wmd.amber_exe_dir))
                # run various analysis scripts
                # b-factor and rmsd
                frun.write('%s/ptraj prot.top &lt;&lt; EOF\n' % (wmd.amber_exe_dir))
                frun.write('trajin min_fin.pdb\n')
                frun.write('trajin md.trj\n')
                frun.write('strip :WAT\n')
                frun.write('strip \'@Cl-\'\n')
                frun.write('strip \'@Na+\'\n')
                frun.write('strip \'@H*\'\n')
                frun.write('rms first out md_rmsd_allheavy.txt\n')
                frun.write('rms first out md_rmsd_backbone.txt @CA,C,N\n')
                frun.write('atomicfluct out md_bfact_tmp.txt byatom bfactor\n')
                frun.write('atomicfluct out md_bfact.txt byres bfactor\n')
                frun.write('EOF\n')
#                frun.write('mv md_bfact_tmp.pdb.1 

                frun.write('%s/ptraj prot.top &lt;&lt; EOF\n' % (wmd.amber_exe_dir))
                frun.write('trajin min_fin.pdb\n')
                frun.write('strip :WAT\n')
                frun.write('strip \'@H*\'\n')
                frun.write('strip \'@Cl-\'\n')
                frun.write('strip \'@Na+\'\n')
                frun.write('trajout md_bfact_tmp.pdb pdb\n')
                frun.write('EOF\n')

                frun.write('touch md.done\n')

        # GROMACS
        else:
            frun.write('amb2gmx_ML.pl --prmtop prot.top --crd prot.trj --outname prot_min\n')
            frun.write('mv prot.top prot_amber.top\n')
            frun.write('mv prot_min.top prot.top\n')
            # write min.mdp
            if 1:
		fout = open('min.mdp','w')
		fout.write(';\n;energy minimization\n;\n;\n;\n')
                fout.write('title               = energy_minimization\n')
                fout.write('cpp                 = /usr/bin/cpp\n')
                fout.write('define              = -DFLEXIBLE\n')
                fout.write('constraints         = none\n')
                fout.write('integrator          = steep\n')
		tmpi = int(wmd.min_steps)
                fout.write('nsteps              = %d\n' % (tmpi))
                fout.write(';\n')
                fout.write('; Output specifications\n')
                fout.write(';\n')
                fout.write('nstlog             = %d\n' % (wmd.min_freqout))
                fout.write('nstxout             = %d\n' % (wmd.min_freqout))
                fout.write('nstenergy           = %d\n' % (wmd.min_freqout))
                fout.write('energygrps          = protein wat %s\n' % (tmp_ligname))
                fout.write(';\n')
                fout.write('; Force field specifications\n')
                fout.write(';\n')
                fout.write('nstlist             = 10\n')
                fout.write('ns_type             = grid\n')
                fout.write('rlist               = 1.0\n')
                fout.write('coulombtype         = PME\n')
                fout.write('rcoulomb            = 1.0\n')
                fout.write('rvdw                = 1.4\n')
                fout.write('vdwtype             = Cut-off\n')
                fout.write('fourierspacing      = 0.12\n')
                fout.write('fourier_nx          = 0\n')
                fout.write('fourier_ny          = 0\n')
                fout.write('fourier_nz          = 0\n')
                fout.write('pme_order           = 4\n')
                fout.write('ewald_rtol          = 1e-5\n')
                fout.write('optimize_fft        = yes\n')
                fout.write(';\n')
                fout.write('; Energy minimization specifications\n')
                fout.write(';\n')
                fout.write('emtol               = 1000.0\n')
                fout.write('emstep              = 0.01\n')
		fout.close()

                frun.write('grompp -f min.mdp -c prot_min.gro -p prot.top -o prot_min.tpr -np %d -maxwarn 50\n' % (wmd.num_proc))
		# generate pdb file for final structure
		frun.write('nohup mpirun -np %d mdrun -s prot_min.tpr -o prot_min.trr -c prot_pr.gro -g min.log -e min.edr\n' % (wmd.num_proc))
                frun.write('trjconv -f prot_min.trr -o prot_min.pdb -s prot_min.tpr &lt;&lt; 0\n')
                frun.write('touch min.done\n')

            if wmd.v_pr_yes.get() == 1:
		fout = open('pr.mdp','w')
                fout.write(';\n')
                fout.write('; position restraint\n')
                fout.write(';\n')
                fout.write(';\n')
                fout.write(';\n')
                fout.write('title		=  position_restraint\n')
                fout.write('cpp                 =  /usr/bin/cpp\n')
                fout.write('define              =  -DPOSRES\n')
                fout.write('constraints         =  hbonds\n')
                fout.write('lincs_order         =  8\n')
                fout.write('lincs_iter          =  5\n')
                fout.write('lincs_warnangle     =  40\n')
                fout.write('integrator          =  md\n')
		tmpi = int(wmd.pr_steps)
                fout.write('dt		        =  %f\n' % (wmd.pr_timestep/1000.))
                fout.write('nsteps              =  %d\n' % (tmpi))
                fout.write(';\n')
                fout.write('; Center-of-mass specifications\n')
                fout.write(';\n')
                fout.write('comm_mode   	= Angular\n')
                fout.write('comm_grps		= protein non-protein\n')
                fout.write('nstcomm		= 1\n')
                fout.write(';\n')
                fout.write('; Output specifications\n')
                fout.write(';\n')
                fout.write('nstxout             = %d\n' % (wmd.pr_freqout))
                fout.write('nstvout             = %d\n' % (wmd.pr_freqout))
                fout.write('nstfout             = 0\n')
                fout.write('nstlog              = %d\n' % (wmd.pr_freqout))
                fout.write('nstenergy           = %d\n' % (wmd.pr_freqout))
                fout.write('energygrps          = protein wat %s\n' % (tmp_ligname))
                fout.write(';\n')
                fout.write('; Force field specifications\n')
                fout.write(';\n')
                fout.write('nstlist             = 10\n')
                fout.write('ns_type             = grid\n')
                fout.write('rlist               = 1.0\n')
                fout.write('coulombtype         = PME\n')
                fout.write('rcoulomb            = 1.0\n')
                fout.write('rvdw                = 1.4\n')
                fout.write('vdwtype             = Cut-off\n')
                fout.write('fourierspacing      = 0.12\n')
                fout.write('fourier_nx          = 0\n')
                fout.write('fourier_ny          = 0\n')
                fout.write('fourier_nz          = 0\n')
                fout.write('pme_order           = 4\n')
                fout.write('ewald_rtol          = 1e-5\n')
                fout.write('optimize_fft        = yes\n')
                fout.write(';\n')
                fout.write('; Berendsen temperature coupling is on in four groups\n')
                fout.write('Tcoupl 		= berendsen\n')
                fout.write('tau_t 		= 0.1 	  0.1\n')
                fout.write('tc_grps 	        = protein non-protein\n')
                fout.write('ref_t 		= 300 	  300\n')
                fout.write(';\n')
                fout.write('; Pressure coupling is on\n')
                fout.write('Pcoupl 		= Parrinello-Rahman\n')
                fout.write('pcoupltype 	        = isotropic\n')
                fout.write('tau_p 		= 0.5\n')
                fout.write('compressibility     = 4.5e-5\n')
                fout.write('ref_p 		= 1.0\n')
                fout.write(';\n')
                fout.write('; Generate velocites is on at 300 K.\n')
                fout.write('gen_vel             = yes\n')
                fout.write('gen_temp            = 300.0\n')
                fout.write('gen_seed            = 123456\n')
		fout.close()

                frun.write('grompp -f pr.mdp -c prot_pr.gro -p prot.top -o prot_pr.tpr -np %d -maxwarn 50\n' % (wmd.num_proc))
		# generate pdb file for final structure
		frun.write('nohup mpirun -np %d mdrun -s prot_pr.tpr -o prot_pr.trr -c prot_equ.gro -g pr.log -e pr.edr\n' % (wmd.num_proc))
                frun.write('trjconv -f prot_pr.trr -o prot_pr.pdb -s prot_pr.tpr &lt;&lt; 0\n')
                frun.write('touch pr.done\n')

            if wmd.v_equ_yes.get() == 1:
		fout = open('equ.mdp','w')
                fout.write(';\n')
                fout.write('; equilibration\n')
                fout.write(';\n')
                fout.write(';\n')
                fout.write(';\n')
                fout.write('title		=  equilibration\n')
                fout.write('cpp                 =  /usr/bin/cpp\n')
                fout.write('constraints         =  hbonds\n')
                fout.write('lincs_order         =  8\n')
                fout.write('lincs_iter          =  5\n')
                fout.write('lincs_warnangle     =  40\n')
                fout.write('integrator          =  md\n')
		tmpi = int(wmd.equ_steps)
                fout.write('dt		        =  %f\n' % (wmd.equ_timestep/1000.))
                fout.write('nsteps              =  %d\n' % (tmpi))
                fout.write(';\n')
                fout.write('; Center-of-mass specifications\n')
                fout.write(';\n')
                fout.write('comm_mode   	= Angular\n')
                fout.write('comm_grps		= protein non-protein\n')
                fout.write('nstcomm		= 1\n')
                fout.write(';\n')
                fout.write('; Output specifications\n')
                fout.write(';\n')
                fout.write('nstxout             = %d\n' % (wmd.equ_freqout))
                fout.write('nstvout             = %d\n' % (wmd.equ_freqout))
                fout.write('nstfout             = 0\n')
                fout.write('nstlog              = %d\n' % (wmd.equ_freqout))
                fout.write('nstenergy           = %d\n' % (wmd.equ_freqout))
                fout.write('energygrps          = protein wat %s\n' % (tmp_ligname))
                fout.write(';\n')
                fout.write('; Force field specifications\n')
                fout.write(';\n')
                fout.write('nstlist             = 10\n')
                fout.write('ns_type             = grid\n')
                fout.write('rlist               = 1.0\n')
                fout.write('coulombtype         = PME\n')
                fout.write('rcoulomb            = 1.0\n')
                fout.write('rvdw                = 1.4\n')
                fout.write('vdwtype             = Cut-off\n')
                fout.write('fourierspacing      = 0.12\n')
                fout.write('fourier_nx          = 0\n')
                fout.write('fourier_ny          = 0\n')
                fout.write('fourier_nz          = 0\n')
                fout.write('pme_order           = 4\n')
                fout.write('ewald_rtol          = 1e-5\n')
                fout.write('optimize_fft        = yes\n')
                fout.write(';\n')
                fout.write('; Berendsen temperature coupling is on in four groups\n')
                fout.write('Tcoupl 		= nose-hoover\n')
                fout.write('tau_t 		= 0.1 	  0.1\n')
                fout.write('tc_grps 	        = protein non-protein\n')
                fout.write('ref_t 		= 300 	  300\n')
                fout.write(';\n')
                fout.write('; Pressure coupling is on\n')
                fout.write('Pcoupl 		= Parrinello-Rahman\n')
                fout.write('pcoupltype 	        = isotropic\n')
                fout.write('tau_p 		= 0.5\n')
                fout.write('compressibility     = 4.5e-5\n')
                fout.write('ref_p 		= 1.0\n')
                fout.write(';\n')
                fout.write('; Generate velocites is on at 300 K.\n')
                fout.write('gen_vel             = yes\n')
                fout.write('gen_temp            = 300.0\n')
                fout.write('gen_seed            = 123456\n')
		fout.close()

                frun.write('grompp -f equ.mdp -c prot_equ.gro -p prot.top -o prot_equ.tpr -np %d -maxwarn 50\n' % (wmd.num_proc))
		# generate pdb file for final structure
		frun.write('nohup mpirun -np %d mdrun -s prot_equ.tpr -o prot_equ.trr -c prot_md.gro -g equ.log -e equ.edr\n' % (wmd.num_proc))
                frun.write('trjconv -f prot_equ.trr -o prot_equ.pdb -s prot_equ.tpr &lt;&lt; 0\n')
                frun.write('touch equ.done\n')

            if wmd.v_md_yes.get() == 1:
		fout = open('md.mdp','w')
                fout.write(';\n')
                fout.write('; md\n')
                fout.write(';\n')
                fout.write(';\n')
                fout.write(';\n')
                fout.write('title		=  md\n')
                fout.write('cpp                 =  /usr/bin/cpp\n')
                fout.write('constraints         =  hbonds\n')
                fout.write('lincs_order         =  8\n')
                fout.write('lincs_iter          =  5\n')
                fout.write('lincs_warnangle     =  40\n')
                fout.write('integrator          =  md\n')
		tmpi = int(wmd.md_steps)
                fout.write('dt		        =  %f\n' % (wmd.md_timestep/1000.))
                fout.write('nsteps              =  %d\n' % (tmpi))
                fout.write(';\n')
                fout.write('; Center-of-mass specifications\n')
                fout.write(';\n')
                fout.write('comm_mode   	= Angular\n')
                fout.write('comm_grps		= protein non-protein\n')
                fout.write('nstcomm		= 1\n')
                fout.write(';\n')
                fout.write('; Output specifications\n')
                fout.write(';\n')
                fout.write('nstxout             = %d\n' % (wmd.md_freqout))
                fout.write('nstvout             = %d\n' % (wmd.md_freqout))
                fout.write('nstfout             = 0\n')
                fout.write('nstlog              = %d\n' % (wmd.md_freqout))
                fout.write('nstenergy           = %d\n' % (wmd.md_freqout))
                fout.write('energygrps          = protein wat %s\n' % (tmp_ligname))
                fout.write(';\n')
                fout.write('; Force field specifications\n')
                fout.write(';\n')
                fout.write('nstlist             = 10\n')
                fout.write('ns_type             = grid\n')
                fout.write('rlist               = 1.0\n')
                fout.write('coulombtype         = PME\n')
                fout.write('rcoulomb            = 1.0\n')
                fout.write('rvdw                = 1.4\n')
                fout.write('vdwtype             = Cut-off\n')
                fout.write('fourierspacing      = 0.12\n')
                fout.write('fourier_nx          = 0\n')
                fout.write('fourier_ny          = 0\n')
                fout.write('fourier_nz          = 0\n')
                fout.write('pme_order           = 4\n')
                fout.write('ewald_rtol          = 1e-5\n')
                fout.write('optimize_fft        = yes\n')
                fout.write(';\n')
                fout.write('; Berendsen temperature coupling is on in four groups\n')
                fout.write('Tcoupl 		= nose-hoover\n')
                fout.write('tau_t 		= 0.1 	  0.1\n')
                fout.write('tc_grps 	        = protein non-protein\n')
                fout.write('ref_t 		= 300 	  300\n')
                fout.write(';\n')
                fout.write('; Pressure coupling is on\n')
                fout.write('Pcoupl 		= Parrinello-Rahman\n')
                fout.write('pcoupltype 	        = isotropic\n')
                fout.write('tau_p 		= 0.5\n')
                fout.write('compressibility     = 4.5e-5\n')
                fout.write('ref_p 		= 1.0\n')
                fout.write(';\n')
                fout.write('; Generate velocites is on at 300 K.\n')
                fout.write('gen_vel             = yes\n')
                fout.write('gen_temp            = 300.0\n')
                fout.write('gen_seed            = 123456\n')
		fout.close()

                frun.write('grompp -f md.mdp -c prot_md.gro -p prot.top -o prot_md.tpr -np %d -maxwarn 50\n' % (wmd.num_proc))
		# generate pdb file for final structure
		frun.write('nohup mpirun -np %d mdrun -s prot_md.tpr -o prot_md.trr -c prot_fin.gro -g md.log -e md.edr\n' % (wmd.num_proc))
                frun.write('trjconv -f prot_md.trr -o prot_md.pdb -s prot_md.tpr &lt;&lt; 0\n')
                frun.write('touch md.done\n')

	frun.close()

	# run tleap on complex
        fcom = open('RunCommands', 'w')
        fcom.write('dos2unix prot_lig.pdb\n')
        fcom.write('dos2unix tmp.lib\n')
        fcom.write('dos2unix tmp.frcmod\n')
        fcom.write('dos2unix leapP.in\n')
        fcom.write('dos2unix min.in\n')
        fcom.write('%s/exe/tleap -f leapP.in\n' % (amber_dir))
        fcom.close()
        
#        os.system('mkdir %s' % (d_md_dir.project_dir_short))
        for j in cof_flag:
            os.system('cp %s/%s.lib %s/%s.frcmod ./tmp_amber/' % (library_dir, filename_cofactors[j], library_dir, filename_cofactors[j]))

        if md_program == 'amber': 
#            os.system('cp prot_lig.pdb prot_lig_SIE.pdb tmp.lib tmp.frcmod leap*.in RunCommands ./%s/' % (d_md_dir.project_dir_short))
            os.system('chmod u+rwx RunCommands; ./RunCommands')
#            os.system('cp ./%s/prot.top ./%s/prot.trj .' % (d_md_dir.project_dir_short, d_md_dir.project_dir_short, d_md_dir.project_dir_short, d_md_dir.project_dir_short))
        else:
#            os.system('cp prot_lig.pdb tmp.lib tmp.frcmod *.in *.mdp RunCommands RunScript ./%s/' % (d_md_dir.project_dir_short))
            os.system('chmod u+rwx RunCommands; ./RunCommands')
#            os.system('cp ./%s/*.mdp ./%s/RunScript ./%s/prot.top ./%s/prot_em.gro .' % (d_md_dir.project_dir_short, d_md_dir.project_dir_short, d_md_dir.project_dir_short, d_md_dir.project_dir_short))

	if os.path.exists('prot.top') == 0:
		tkMessageBox.showinfo('Problem in preparing MD simulation','Please check initial structure of protein-ligand complex.')
		return 0
        


        # copy files for actual simulation
        if md_program == 'amber': 
            if wmd.local_or_server == 0:
                os.system('mkdir %s' % (d_md_dir.project_dir_short))
                os.system('cp prot.top prot.trj *.in RunScript ./%s/' % (d_md_dir.project_dir_short))
            else:
                os.system("ssh -p %d %s@%s 'cd %s; mkdir %s'" % (wmd.ssh_port, username, wmd.computer_name, wmd.home_dir, d_md_dir.project_dir_short))
                os.system('scp -P %d prot.top prot.trj *.in RunScript %s@%s:%s/%s/' % (wmd.ssh_port, username, wmd.computer_name, wmd.home_dir, d_md_dir.project_dir_short))
        else:
            pass



        if wmd.run_settings == 'prep':
            if wmd.local_or_server == 0:
                childp = subprocess.Popen('cd ./%s; chmod u+rwx RunScript' % (d_md_dir.project_dir_short), shell=True)
                tkMessageBox.showinfo('Preparation of MM calculation done',"Please enter folder %s_client/%s and start job by typing 'nohup ./RunScript &amp;'.\nData can be read in by using 'Amber, Monitor molecular mechanics results'." % (d_md_dir.project_dir, d_md_dir.project_dir))
            else:
                childp = subprocess.Popen("ssh -p %d %s@%s 'cd %s/%s; chmod u+rwx RunScript'" % (wmd.ssh_port, username, wmd.computer_name, wmd.home_dir, d_md_dir.project_dir_short), shell=True)
                tkMessageBox.showinfo('Preparation of MM calculation done',"Please copy folder %s_client/%s to server and start job by typing 'nohup ./RunScript &amp;'.\nData can be read in by using 'Amber, Monitor molecular mechanics results'." % (d_md_dir.project_dir, d_md_dir.project_dir))
        else:
            if wmd.local_or_server == 0:
                childp = subprocess.Popen('cd ./%s; chmod u+rwx RunScript; nohup ./RunScript &amp;' % (d_md_dir.project_dir_short), shell=True)
                tkMessageBox.showinfo('Preparation of MM calculation done',"Job has been started on localhost.\nData can be read in by using 'Amber, Monitor molecular mechanics results'.")
            else:
                childp = subprocess.Popen("ssh -p %d %s@%s 'cd %s/%s; chmod u+rwx RunScript; /usr/pbs/bin/qsub -q %s RunScript'" % (wmd.ssh_port, username, wmd.computer_name, wmd.home_dir, d_md_dir.project_dir_short, wmd.queue_name), shell=True)
                tkMessageBox.showinfo('Preparation of MM calculation done',"Job has been started on server.\nData can be read in by using 'Amber, Monitor molecular mechanics results'.")
   


        if md_program == 'amber':
#            if wmd.v_min_yes.get() == 1:
#                os.remove('min.in') 
#            if wmd.v_pr_yes.get() == 1:
#                os.remove('pr.in') 
#            if wmd.v_equ_yes.get() == 1:
#                os.remove('equ.in') 
#            if wmd.v_md_yes.get() == 1:
#                os.remove('md.in') 
            os.remove('leapP.in') 
            try:
                os.remove('prot.top')
            except:
                pass
                
            try:
                os.remove('prot.trj')
            except:
                pass
                
            try:
                os.remove('prot_lig.pdb')
            except:
                pass
                
            try:
                os.remove('prot_out.pdb')
            except:
                pass
                
            try:
                os.remove('RunCommands')
            except:
                pass
                
            try:
                os.remove('RunScript')
            except:
                pass
                
            try:
                shutil.move('tmp.frcmod', '%s.frcmod' % tmp_ligname)
            except:
                pass
                
            try:
                shutil.move('tmp.lib', '%s.lib' % tmp_ligname)
            except:
                pass
                
            try:
                os.remove('tmp.mol2')
            except:
                pass
                
            try:
                os.remove('tmp.prepin')
            except:
                pass
                

#        os.chmod('RunScript', S_IRWXU)
#	os.system('chmod a+x RunScript') 
     
#	os.system('rm tmp.*')

	os.chdir(curdir)

	print('preparation for md simulation done')

#######################################################################################
def md_import(app):
        global monitor_list
        
	ftypes=(('prg file', '*.prg'), ('All files', '*'))
	curdir = os.getcwd()
	openfile = askopenfilename(initialdir=curdir,
                                   filetypes=ftypes)
	if openfile:
            indir = os.path.dirname(openfile)
            os.chdir(indir)
            
            fin = open(openfile, 'r')
            tmp = fin.readline()
            md_prog = tmp.strip()
            tmp = fin.readline()
            proj_user = tmp.strip()
            tmp = fin.readline()
            proj_computer = tmp.strip()
            tmp = fin.readline()
            proj_port = int(tmp.strip())
            tmp = fin.readline()
            proj_home = tmp.strip()
            tmp = fin.readline()
            proj_dir = tmp.strip()
            
            if proj_computer == 'local':
                os.system('cp ./%s/*.done .' % (proj_dir))
            else:
                os.system('scp -P %d %s@%s:%s/%s/*.done .' % (proj_port, proj_user, proj_computer, proj_home, proj_dir))
            
            monitor_list = []
            for ent in os.listdir(indir):
                if ent.find('.done') &gt; 0:
                    monitor_list.append(ent)
#            print monitor_list
            
        d_monitor = monitor_dialog(app.root)
	if d_monitor.ok_flag == 0:
		return 0
        
        if md_prog == 'amber':
            flag_trj = 0
            for ent in os.listdir(indir):
                if ent.find('prot.top') == 0:
                    flag_trj = 1
            if flag_trj == 0:
                if proj_computer == 'local':
                    os.system('cp ./%s/prot.top .' % (proj_dir))
                else:
                    os.system('scp -P %d %s@%s:%s/%s/prot.top .' % (proj_port, proj_user, proj_computer, proj_home, proj_dir))
            for i in monitor_list:
                if i == 'min.done':
                    flag_trj = 0
                    for ent in os.listdir(indir):
#                        print 'min.trj: %s %s %d' % (indir, ent, ent.find('min.trj'))
                        if ent.find('min.trj') == 0:
                            flag_trj = 1
                    if flag_trj == 0:
                        if proj_computer == 'local':
                            os.system('cp ./%s/min_fin.pdb ./%s/min.out ./%s/min.trj .' % (proj_dir, proj_dir, proj_dir))
                        else:
                            os.system('scp -P %d %s@%s:%s/%s/min_fin.pdb %s@%s:%s/%s/min.out %s@%s:%s/%s/min.trj .' % (proj_port, proj_user, proj_computer, proj_home, proj_dir, proj_user, proj_computer, proj_home, proj_dir, proj_user, proj_computer, proj_home, proj_dir))
                    if d_monitor.min_whattodo == 'visual':
                        cmd.load('min_fin.pdb', 'min_fin')
            for i in monitor_list:
                if i == 'pr.done':
                    flag_trj = 0
                    for ent in os.listdir(indir):
                        if ent.find('pr.trj') == 0:
                            flag_trj = 1
                    if flag_trj == 0:
                        if proj_computer == 'local':
                            os.system('cp ./%s/pr_fin.pdb ./%s/pr_rmsd* ./%s/pr.out ./%s/pr.trj .' % (proj_dir, proj_dir, proj_dir, proj_dir))
                        else:
                            os.system('scp -P %d %s@%s:%s/%s/pr_fin.pdb %s@%s:%s/%s/pr_rmsd* %s@%s:%s/%s/pr.out %s@%s:%s/%s/pr.trj .' % (proj_port, proj_user, proj_computer, proj_home, proj_dir, proj_user, proj_computer, proj_home, proj_dir, proj_user, proj_computer, proj_home, proj_dir, proj_user, proj_computer, proj_home, proj_dir))
                    if d_monitor.pr_whattodo == 'visual':
                        cmd.load('prot.top', 'pr_traj')
                        cmd.load_traj('pr.trj', 'pr_traj')
            for i in monitor_list:
                if i == 'equ.done':
                    flag_trj = 0
                    for ent in os.listdir(indir):
                        if ent.find('equ.trj') == 0:
                            flag_trj = 1
                    if flag_trj == 0:
                        if proj_computer == 'local':
                            os.system('cp ./%s/equ_fin.pdb ./%s/equ_rmsd* ./%s/equ.out ./%s/equ.trj .' % (proj_dir, proj_dir, proj_dir, proj_dir))
                        else:
                            os.system('scp -P %d %s@%s:%s/%s/equ_fin.pdb %s@%s:%s/%s/equ_rmsd* %s@%s:%s/%s/equ.out %s@%s:%s/%s/equ.trj .' % (proj_port, proj_user, proj_computer, proj_home, proj_dir, proj_user, proj_computer, proj_home, proj_dir, proj_user, proj_computer, proj_home, proj_dir, proj_user, proj_computer, proj_home, proj_dir))
                    if d_monitor.equ_whattodo == 'visual':
                        cmd.load('prot.top', 'equ_traj')
                        cmd.load_traj('equ.trj', 'equ_traj')
            for i in monitor_list:
                if i == 'md.done':
                    flag_trj = 0
                    for ent in os.listdir(indir):
                        if ent.find('md.trj') == 0:
                            flag_trj = 1
                    if flag_trj == 0:
                        if proj_computer == 'local':
                            os.system('cp ./%s/md_fin.pdb ./%s/md.out ./%s/md.trj .' % (proj_dir, proj_dir, proj_dir))
                        else:
                            os.system('scp -P %d %s@%s:%s/%s/md_fin.pdb %s@%s:%s/%s/md.out %s@%s:%s/%s/md.trj .' % (proj_port, proj_user, proj_computer, proj_home, proj_dir, proj_user, proj_computer, proj_home, proj_dir, proj_user, proj_computer, proj_home, proj_dir))
                    if proj_computer == 'local':
                        os.system('cp ./%s/md_rmsd* ./%s/md_bfact* .' % (proj_dir, proj_dir))
                    else:
                        os.system('scp -P %d %s@%s:%s/%s/md_rmsd* %s@%s:%s/%s/md_bfact* .' % (proj_port, proj_user, proj_computer, proj_home, proj_dir, proj_user, proj_computer, proj_home, proj_dir))
                    if d_monitor.md_whattodo == 'visual':
                        cmd.load('prot.top', 'md_traj')
                        cmd.load_traj('md.trj', 'md_traj')
                    # determine pdb b-factor file
                    fpdb_in = open('md_bfact_tmp.pdb.1', 'r')
                    fdat_in = open('md_bfact_tmp.txt', 'r')
                    fpdb_out = open('md_bfact.pdb', 'w')
                    for j in fpdb_in:
                        if j.find('ATOM') == 0:
                            k = fdat_in.readline()
                            m  = k.strip()
                            tmp, bfact = m.split(None, 1)
                            fpdb_out.write('%s%6.2f\n' % (j[0:60], float(bfact)))
                        else:
                            fpdb_out.write(j)
                    fpdb_in.close()
                    fdat_in.close()
                    fpdb_out.close()
#                    os.remove('md_bfact_tmp.pdb.1')
#                    os.remove('md_bfact_tmp.txt')
                    # extract energies
                    fen_in = open('md.out', 'r')
                    fen_out = open('md_energies.txt', 'w')
                    fen_out.write(' Time[ps]     Temperature   Total energy   Kinetic energy  Potential energy\n')
                    cj = 0
                    while fen_in:
                        i = fen_in.readline()
                        if i.find('A V E R A G E S') &gt;= 0:
                            break
                        if i.find('NSTEP') &gt;= 0:
                            time = float(i[30:42])
                            temp = float(i[53:62])
                            j = fen_in.readline()
                            etot = float(j[9:24])
                            ektot = float(j[35:50])
                            eptot = float(j[64:79])
                            if cj != 0:
                                fen_out.write('%10.2f    %10.2f   %12.2f    %12.2f    %12.2f\n' % (time, temp, etot, ektot, eptot))
                            cj += 1
                    fen_in.close()
                    fen_out.close()
                            
                            
                        
        else:
            if proj_computer == 'local':
                os.system('cp ./%s/*.pdb .' % (proj_dir))
            else:
                os.system('scp -P %d %s@%s:%s/%s/*.pdb .' % (proj_port, proj_user, proj_computer, proj_home, proj_dir))
            for i in monitor_list:
                if i == 'min.done' and d_monitor.min_whattodo == 'visual':
                    cmd.load('prot_min.pdb', 'min_traj')
            for i in monitor_list:
                if i == 'pr.done' and d_monitor.pr_whattodo == 'visual':
                    cmd.load('prot_pr.pdb', 'pr_traj')
            for i in monitor_list:
                if i == 'equ.done' and d_monitor.equ_whattodo == 'visual':
                    cmd.load('prot_equ.pdb', 'equ_traj')
            for i in monitor_list:
                if i == 'md.done' and d_monitor.md_whattodo == 'visual':
                    cmd.load('prot_md.pdb', 'md_traj')
            


#        del monitor_list[:]
        os.chdir(curdir)
        

#######################################################################################
def calculate_SIE(app):
	ftypes=(('prg file', '*.prg'), ('All files', '*'))
	curdir = os.getcwd()
	openfile = askopenfilename(initialdir=curdir, filetypes=ftypes)
	if openfile:
            indir = os.path.dirname(openfile)
            os.chdir(indir)

            fin = open(openfile, 'r')
            tmp = fin.readline()
            md_prog = tmp.strip()
            if md_prog != 'amber':
		tkMessageBox.showwarning('Simulation was not performed with AMBER', 'SIE currently works only with AMBER output trajectories.')
		return 0
            
            tmp = fin.readline()
            proj_user = tmp.strip()
            tmp = fin.readline()
            proj_computer = tmp.strip()
            tmp = fin.readline()
            proj_port = int(tmp.strip())
            tmp = fin.readline()
            proj_home = tmp.strip()
            tmp = fin.readline()
            proj_dir = tmp.strip()
                        
            tmp = fin.readline()
            m0, m1, m2, m3 = tmp.split(None, 3)
            tar_beg = int(m0)
            tar_end = int(m1)
            lig_beg = int(m2)
            lig_end = int(m3)
            
            # check if SIE was already performed in project
            flag = 0
            for ent in os.listdir(indir):
                if ent.find('sie_ave.out') &gt; -1:
                    if tkMessageBox.askokcancel('SIE analysis', 'SIE results found. Do you want to overwrite results?') == 0:
                        flag = 1
            if flag == 0:
                flag = 0
                for ent in os.listdir(indir):
                    if ent.find('md.done') &gt; -1:
                        flag = 1
                if flag == 0:
                    if proj_computer == 'local':
                        os.system('cp ./%s/*.done .' % (proj_dir))
                    else:
                        os.system('scp -P %d %s@%s:%s/%s/*.done .' % (proj_port, proj_user, proj_computer, proj_home, proj_dir))
                    flag = 0
                    for ent in os.listdir(indir):
                        if ent.find('md.done') &gt; -1:
                            flag = 1
                    if flag == 0:
                        tkMessageBox.showwarning("Simulation hasn't finished production yet.", 'Simulation might have crashed or is still running.')
                        return 0
                    
                    if proj_computer == 'local':
                        os.system('cp ./%s/prot.top ./%s/md.trj ./%s/md.in .' % (proj_dir, proj_dir, proj_dir))
                    else:
                        os.system('scp -P %d %s@%s:%s/%s/prot.top %s@%s:%s/%s/md.trj %s@%s:%s/%s/md.in .' % (proj_port, proj_user, proj_computer, proj_home, proj_dir, proj_user, proj_computer, proj_home, proj_dir, proj_user, proj_computer, proj_home, proj_dir))
                    
                d_sie = sie_dialog(app.root)
                if d_sie.ok_flag == 0:
                    return 0
        
            
                fcom = open('RunSIE', 'w')
                fcom.write('%s/exe/ptraj prot.top &lt;&lt; EOF\n' % (amber_dir))
                fcom.write('trajin md.trj\n')
                fcom.write('strip :WAT\n')
                fcom.write('strip \'@Cl-\'\n')
                fcom.write('strip \'@Na+\'\n')
                fcom.write('trajout md_SIE.trj nobox\n')
                fcom.write('EOF\n')
                fcom.write('%s/bin/sietraj -pt prot_SIE.top -trj md_SIE.trj -sf %d -ef %d -inc %d -tr %d-%d -lr %d-%d -o sie.out -sie\n' % (sie_dir, d_sie.start_frame, d_sie.end_frame, d_sie.interval, tar_beg, tar_end, lig_beg, lig_end))
                fcom.write('%s/bin/sietraj -ave sie.out &gt; sie_ave.out\n' % (sie_dir))
                fcom.close()
            
            
                os.system('chmod u+rwx RunSIE; ./RunSIE')
                
                fo = open('sie.txt', 'w')
                fo.write('        dG       vdW,scaled  Coul,scaled  Reac.F.,scaled  Cavity,scaled   Constant        vdW             Coul     React.Field     Cavity\n')
                for i in open('sie.out'):
                    a1, a2, a3, a4, a5, a6, a7, a8, a9 = i.split(None, 8)
                    alpha= 0.104758
                    gamma= 0.012894
                    const= -2.89

                    vdw = float(a7)
                    els = float(a8)
                    rf = float(a3)
                    cavity = gamma*float(a9)
                    dg = float(a2)
                    fo.write('% 12.3f  % 12.3f  % 12.3f  % 12.3f  % 12.3f  % 12.3f  % 12.3f  % 12.3f  % 12.3f  % 12.3f\n' % (dg, vdw*alpha, els*alpha, rf*alpha, cavity*alpha, const, vdw, els, rf, cavity))
                fo.close()
            
            sie_results(app.root)
        os.chdir(curdir)

#######################################################################################
def calculate_MMPBSA(app):
        global non_prot_res_list
        global non_prot_res_list_amber
        global d_mmpbsa_ligands
	listres = ['ALA', 'ARG', 'ASH', 'ASN', 'ASP', 'CYS', 'CYN', 'CYX', 'CY1', 'GLH', 'GLN', 'GLU', 'GLY', 'HIS', 'HIE', 'HID', 'HIP', 'ILE', 'LEU', 'LYS', 'LYP', 'MET', 'PHE', 'PRO', 'SER', 'THR', 'TRP', 'TYR', 'VAL']
        listres_water = ['ALA', 'ARG', 'ASH', 'ASN', 'ASP', 'CYS', 'CYN', 'CYX', 'CY1', 'GLH', 'GLN', 'GLU', 'GLY', 'HIS', 'HIE', 'HID', 'HIP', 'ILE', 'LEU', 'LYS', 'LYP', 'MET', 'PHE', 'PRO', 'SER', 'THR', 'TRP', 'TYR', 'VAL', 'WAT', 'SOL', 'HOH']
        listres_plus_cofactors = listres
        for i in PDBcode_cofactors:
            listres_plus_cofactors.append(i)
        cof_flag = []


        curdir = os.getcwd()
        
        # select input format: GROMACS/AmberFF or AMBER/AmberFF
	d_mmpbsa_format = mmpbsa_format_dialog(app.root)
	if d_mmpbsa_format.ok_flag == 0:
		return 0
        # select input topology and trajectory
        d_mmpbsa_source = mmpbsa_source_dialog(app.root, flag_source = d_mmpbsa_format.mmpbsa_source)
	if d_mmpbsa_source.ok_flag == 0:
		return 0
            
        if d_mmpbsa_format.mmpbsa_source == 'gro':
            #-----------------------------------------------------------------------
            # GROMACS input
            mmpbsa_proj_dir = d_mmpbsa_source.dir_out                
            # open ffamber_vs_amber.txt file
            gro_res_list = [[] for i in range(3000)]
            gro_atm_list = [[] for i in range(3000)]
            gro_alt_list = [[] for i in range(3000)]
            amb_res_list = [[] for i in range(3000)]
            amb_atm_list = [[] for i in range(3000)]
            non_prot_res_list = []
            non_prot_res_list_amber = []
            j = 0
            fi = open('%s/ffamber_vs_amber.txt' % (gro_amb_dir))
            for i in fi:
                i2 = i.strip()
                if len(i2) &gt; 4:
                    tmp_gro_res, tmp_gro_atm, tmp_amb_res, tmp_amb_atm = i2.split(None, 3)
    #                print '%s:%s:%s:%s' % (tmp_gro_res, tmp_gro_atm, tmp_amb_res, tmp_amb_atm)
                    gro_res_list[j] = tmp_gro_res.strip()
                    gro_atm_list[j] = tmp_gro_atm.strip()
                    if tmp_gro_atm[0] == '1' or tmp_gro_atm[0] == '2' or tmp_gro_atm[0] == '3' or tmp_gro_atm[0] == '4' or tmp_gro_atm[0] == '5' or tmp_gro_atm[0] == '6' or tmp_gro_atm[0] == '7' or tmp_gro_atm[0] == '8' or tmp_gro_atm[0] == '9':
                        tmp_alt_atm = []
                        ll = len(tmp_gro_atm)
                        for q in range(1, ll):
                            tmp_alt_atm.append(tmp_gro_atm[q])
                        tmp_alt_atm.append(tmp_gro_atm[0])
                        gro_alt_list[j] = ''.join(tmp_alt_atm)
                    else:
                        gro_alt_list[j] = tmp_gro_atm.strip()
                    amb_res_list[j] = tmp_amb_res.strip()
                    amb_atm_list[j] = tmp_amb_atm.strip()
    #                print '%d:%s:%s:%s:%s:%s' % (j, gro_res_list[j], gro_atm_list[j], gro_alt_list[j], amb_res_list[j], amb_atm_list[j])
                    j += 1
            fi.close()
            
            # translate gro into pdb file
            fgro = open(d_mmpbsa_source.file_top, 'r')
            fgro.seek(0)
            fgro.readline()
            line = fgro.readline()
            nn = int(line.strip())
    #        print nn
            fpdb_prot = open('tmp_prot_only.pdb', 'w')
            fpdb_lig  = open('tmp_lig_only.pdb', 'w')
            fpdb_wat  = open('tmp_wat_only.pdb', 'w')
            for k in range(nn):
                line = fgro.readline()
                tmp_resnum = int(line[0:5])
                tmp_resnam = (line[5:9]).strip()
                tmp_atname = (line[11:15]).strip()
                tmp_atnumb = int(line[15:20])
                tmp_x = 10.*float(line[20:28])
                tmp_y = 10.*float(line[28:36])
                tmp_z = 10.*float(line[36:44])
                flag = 0
                for s in listres_plus_cofactors:  
                    if tmp_resnam.find(s) &gt; -1:
                        tmp_resnam = s
                        flag = 1
                        # check for co-factors
                        flag2 = 0
                        for p in cof_flag:
                            if tmp_resnam == PDBcode_cofactors[p]:
                                flag2 = 1
                        if flag2 == 0:
                            cf = 0
                            for pco, fco in zip(PDBcode_cofactors, filename_cofactors):
                                if tmp_resnam.find(pco) &gt; -1:
                                    cof_flag.append(cf)
                                cf += 1
                        break
                if flag == 1:		# only protein residues  
                    for k in range(j):
                        if tmp_resnam == gro_res_list[k] and (tmp_atname == gro_atm_list[k] or tmp_atname == gro_alt_list[k]):
                            tmp_resnam = amb_res_list[k]
                            tmp_atname = amb_atm_list[k]
                            break
                        if tmp_atname == 'OC1':
                            tmp_atname = 'O'
                        elif tmp_atname == 'OC2':
                            tmp_atname = 'OXT'
                    if tmp_atname[0] == '1' or tmp_atname[0] == '2' or tmp_atname[0] == '3' or tmp_atname[0] == '4' or tmp_atname[0] == '5' or tmp_atname[0] == '6' or tmp_atname[0] == '7' or tmp_atname[0] == '8' or tmp_atname[0] == '9' or len(tmp_atname) == 4:
                        fpdb_prot.write('ATOM  % 5d %-4s %-3s  % 4d    % 8.3f% 8.3f% 8.3f\n' % (tmp_atnumb, tmp_atname, tmp_resnam, tmp_resnum, tmp_x, tmp_y, tmp_z))
                    else:
                        fpdb_prot.write('ATOM  % 5d  %-4s%-3s  % 4d    % 8.3f% 8.3f% 8.3f\n' % (tmp_atnumb, tmp_atname, tmp_resnam, tmp_resnum, tmp_x, tmp_y, tmp_z))
                else:
                    if tmp_resnam.find('SOL') &gt; -1 or tmp_resnam.find('HOH') &gt; -1 or tmp_resnam.find('WAT') &gt; -1:
                        if tmp_atname.find('OW') &gt; -1 or tmp_atname.find('O') &gt; -1:
                            fpdb_wat.write('ATOM% 7d  %-4s%-3s% 6d    % 8.3f% 8.3f% 8.3f\n' % (tmp_atnumb, 'O', 'WAT', tmp_resnum, tmp_x, tmp_y, tmp_z))
                        if tmp_atname.find('HW1') &gt; -1 or tmp_atname.find('H1') &gt; -1:
                            fpdb_wat.write('ATOM% 7d  %-4s%-3s% 6d    % 8.3f% 8.3f% 8.3f\n' % (tmp_atnumb, 'H1', 'WAT', tmp_resnum, tmp_x, tmp_y, tmp_z))
                        if tmp_atname.find('HW2') &gt; -1 or tmp_atname.find('H2') &gt; -1:
                            fpdb_wat.write('ATOM% 7d  %-4s%-3s% 6d    % 8.3f% 8.3f% 8.3f\n' % (tmp_atnumb, 'H2', 'WAT', tmp_resnum, tmp_x, tmp_y, tmp_z))
                    else:
                        flag2 = 0
                        for p in non_prot_res_list:
                            if tmp_resnam == p:
                                flag2 = 1
                        if flag2 == 0:
                            non_prot_res_list.append(tmp_resnam)
    #                    fpdb_lig.write('ATOM  % 5d  %-4s%-3s  % 4d    % 8.3f% 8.3f% 8.3f\n' % (tmp_atnumb, tmp_atname, tmp_resnam, tmp_resnum, tmp_x, tmp_y, tmp_z))
                        for k in range(j):
                            if tmp_resnam == gro_res_list[k] and (tmp_atname == gro_atm_list[k] or tmp_atname == gro_alt_list[k]):
                                tmp_resnam = amb_res_list[k]
                                tmp_atname = amb_atm_list[k]
                                break
                        if flag2 == 0:
                            non_prot_res_list_amber.append(tmp_resnam)
                        if tmp_atname[0] == '1' or tmp_atname[0] == '2' or tmp_atname[0] == '3' or tmp_atname[0] == '4' or tmp_atname[0] == '5' or tmp_atname[0] == '6' or tmp_atname[0] == '7' or tmp_atname[0] == '8' or tmp_atname[0] == '9' or len(tmp_atname) == 4:
                            fpdb_prot.write('ATOM  % 5d %-4s %-3s  % 4d    % 8.3f% 8.3f% 8.3f\n' % (tmp_atnumb, tmp_atname, tmp_resnam[0:3], tmp_resnum, tmp_x, tmp_y, tmp_z))
                        else:
                            fpdb_prot.write('ATOM  % 5d  %-4s%-3s  % 4d    % 8.3f% 8.3f% 8.3f\n' % (tmp_atnumb, tmp_atname, tmp_resnam[0:3], tmp_resnum, tmp_x, tmp_y, tmp_z))
            fgro.close()
        else:
            #-----------------------------------------------------------------------
            # AMBER input
            # read pdb file and separate into pdb files without water etc.
            mmpbsa_proj_dir = d_mmpbsa_source.dir_out                
            non_prot_res_list = []
            non_prot_res_list_amber = []
            fpdb = open(d_mmpbsa_source.file_top, 'r')
            fpdb_prot = open('tmp_prot_only.pdb', 'w')
            fpdb_lig  = open('tmp_lig_only.pdb', 'w')
            fpdb_wat  = open('tmp_wat_only.pdb', 'w')
            fpdb.seek(0)
            for i in fpdb:
                if i.find('ATOM') &gt;= 0 or i.find('HETATM') &gt;= 0:
                    tmp_resnam = (i[17:20]).strip()
                    flag = 0
                    for s in listres_plus_cofactors:  
                        if tmp_resnam.find(s) &gt; -1:
                            tmp_resnam = s
                            flag = 1
                            # check for co-factors
                            flag2 = 0
                            for p in cof_flag:
                                if tmp_resnam == PDBcode_cofactors[p]:
                                    flag2 = 1
                            if flag2 == 0:
                                cf = 0
                                for pco, fco in zip(PDBcode_cofactors, filename_cofactors):
                                    if tmp_resnam.find(pco) &gt; -1:
                                        cof_flag.append(cf)
                                        print cof_flag
                                    cf += 1
                            break
                    if flag == 1:		# only protein residues  
                        fpdb_prot.write(i)
                    else:
                        if tmp_resnam.find('SOL') &gt; -1 or tmp_resnam.find('HOH') &gt; -1 or tmp_resnam.find('WAT') &gt; -1:
                            fpdb_wat.write(i)
                        else:
                            flag2 = 0
                            for p in non_prot_res_list:
                                if tmp_resnam == p:
                                    flag2 = 1
                            if flag2 == 0:
                                non_prot_res_list.append(tmp_resnam)
                                non_prot_res_list_amber.append(tmp_resnam)
                            fpdb_prot.write(i)
            fpdb.close()

        # Define how to handle with non-standard protein residues: lig, prot, remove
        d_mmpbsa_ligands = mmpbsa_ligands_dialog(app.root)
	if d_mmpbsa_ligands.ok_flag == 0:
		return 0 
            
        d_mmpbsa_frames = mmpbsa_frames_dialog(app.root, d_mmpbsa_source.file_in)
	if d_mmpbsa_frames.ok_flag == 0:
		return 0 
	print "aa"
#        print d_mmpbsa_ligands.handle_ligand
        flag = 0
        ci = 0
        list_remove_residues = []
        for j in non_prot_res_list:
            if d_mmpbsa_ligands.handle_ligand[ci] == 'lig':
                flag += 1
                lig_name = j
            elif d_mmpbsa_ligands.handle_ligand[ci] == 'remove':
                list_remove_residues.append(j)
            ci += 1
        if flag != 1:
            tkMessageBox.showwarning('More or less than one ligand is selected', 'Please, make sure to select exactly one residue as ligand.')
            return 0
            
        
        fpdb_prot.close()
        fpdb_lig.close()
        fpdb_wat.close()
	print "aaa"
                
        # separate protein from ligand
        fpdb_prot_tmp = open('tmp_prot_only.pdb', 'r')
        fpdb_lig_tmp  = open('tmp_lig_only.pdb', 'r')
        fpdb_prot = open('prot_only.pdb', 'w')
        fpdb_lig  = open('lig_only.pdb', 'w')
        for i in fpdb_prot_tmp:
            tmp_resnam = (i[17:20]).strip()
            ci = 0
            flag = 0
            oldresnam = ' '
#            for j in non_prot_res_list:
            for j in non_prot_res_list_amber:
                if j == tmp_resnam:
                    if d_mmpbsa_ligands.handle_ligand[ci] == 'lig':
                        flag = 1
                    elif d_mmpbsa_ligands.handle_ligand[ci] == 'remove':
                        flag = 2
                ci += 1
            if flag == 0:
                fpdb_prot.write(i)
            if flag == 1:  
                newline = []
                newline.append(i[:22])
                newline.append('   1')
                newline.append(i[26:])
                mm = ''.join(newline)
                fpdb_lig.write(mm)
        
        fpdb_prot.close()
        fpdb_lig.close()
        fpdb_prot_tmp.close()
        fpdb_lig_tmp.close()
	print "bbb"
        
        # Read pdb file and find disulfide bridges
        ci = 0
        for na in cmd.get_names('objects'):
            ci += 1
                
        if ci &gt; 0:
#            if tkMessageBox.askokcancel('Read project', 'Reading project will delete all exisiting objects in current session.') == 0:
#                return 0
            # remove existing objects
            for na in cmd.get_names('objects'):
                cmd.remove(na)
                cmd.delete(na)
        cmd.load('prot_only.pdb')
	stored.chain = []
	stored.resnam = []
	stored.resid = []
	for na in cmd.get_names('objects'):
            try:
                cmd.select('pro', na)
                cmd.select('pro2', 'pro and resn ALA+ARG+ASH+ASN+ASP+CYS+CYX+CY1+GLH+GLN+GLU+GLY+HIS+HIE+HID+HIP+ILE+LEU+LYS+MET+PHE+PRO+SER+THR+TRP+TYR+VAL+HEM+HEO+FAD')
            

                
                L = cmd.count_atoms('pro2')
                if L &gt; 0:
                    rem = na
                    find_disulfide_bridges('pro2') 
                    cmd.select('sele2', 'pro and name CA+FE')
                    cmd.iterate ('sele2', 'stored.chain.append(chain)')
                    cmd.iterate ('sele2', 'stored.resnam.append(resn)')
                    cmd.iterate ('sele2', 'stored.resid.append(resi)')
#                    cmd.save('prot_out.pdb','pro', 0, 'pdb')
                    shutil.copy('prot_only.pdb', 'prot_out.pdb')
                    ResortPDB4Amber('prot_out.pdb') 
                    cmd.delete('sele2')  
                cmd.delete('pro')
                cmd.delete('pro2')
            except:
                pass
     
        # concatenate ligand and protein
	datalist = []
	for line in open('lig_only.pdb'):
            datalist.append(line)
	datalist.append('TER\n')
	for line in open('prot_out.pdb'):
            datalist.append(line)
	fout = open('prot_lig.pdb', 'w')
	fout.writelines(datalist)
	fout.close()
        # add waters
	fout = open('prot_lig_wat.pdb', 'w')
	datalist.append('TER\n')
	for line in open('tmp_wat_only.pdb'):
            datalist.append(line)
	fout.writelines(datalist)
	fout.close()

        fpdb = open('tmp_wat_only.pdb')
        line = fpdb.readline()
        water_atnumb = int(line[4:11])
        fpdb.close()

        list_atomid = []
        fpdb = open('prot_lig_wat.pdb', 'r')
        nn2 = 0
        for i in fpdb:
            if len(i) &gt; 6:
                mm = int(i[6:12])
                list_atomid.append(mm)
                nn2 = nn2 + 1
        print nn2

        if d_mmpbsa_format.mmpbsa_source == 'gro':
            #-----------------------------------------------------------------------
            # GROMACS input
            # convert nmr-pdb file into trj file
            
            fpdb.close()
            fnmr = open(d_mmpbsa_source.file_trj, 'r')
            ftrj = open('md_tmp.trj', 'w')
            ftrj.write('trajectory file for MMPBSA\n')
            
            xx = [0.0 for i in range(3*(nn+1))]
            
            num_frames = 0
            flag_first = 1
            for i in fnmr:
                if i[0:5] == 'MODEL':
                    num_frames += 1
                    cl = 0
                    if flag_first == 0:
                        for k in list_atomid:
                            ftrj.write('% 8.3f' % xx[3*k])
                            cl += 1
                            if cl == 10:
                                ftrj.write('\n')
                                cl = 0
                            ftrj.write('% 8.3f' % xx[3*k+1])
                            cl += 1
                            if cl == 10:
                                ftrj.write('\n')
                                cl = 0
                            ftrj.write('% 8.3f' % xx[3*k+2])
                            cl += 1
                            if cl == 10:
                                ftrj.write('\n')
                                cl = 0
                        if cl &gt; 0:
                            ftrj.write('\n')
                    else:
                        flag_first = 0
                if i[0:4] == 'ATOM' or i[0:6] == 'HETATM':
                    aid = int(i[6:12])
                    xx[3*aid] = float(i[30:38])
                    xx[3*aid+1] = float(i[38:46])
                    xx[3*aid+2] = float(i[46:54])
            fnmr.close()
            ftrj.close()
        else:
            #-----------------------------------------------------------------------
            # AMBER input
            # read number of frames in trj file
            fi = open(d_mmpbsa_source.file_in, 'r')
            for line in fi:
                if line.find('nstlim') &gt; -1:
                    aa1, aa2 = line.split(', ', 1)
                    i = aa1.find('=') + 1
                    num_steps = int(aa1[i:])
                if line.find('ntwx') &gt; -1:
                    aa1, aa2, aa3 = line.split(', ', 2)
                    i = aa2.find('=') + 1
                    num_frq_out = int(aa2[i:])
            num_frames = num_steps/num_frq_out
            
            # remove residues from topology files
            ftraj = open('Run_ptraj', 'w')
            ftraj.write('%s/exe/ptraj prot.top &lt;&lt; EOF\n' % (amber_dir))
            ftraj.write('trajin %s\n' % d_mmpbsa_source.file_trj)
            for i in list_remove_residues:
                ftraj.write('strip :%s\n' % i)
            ftraj.write('trajout md_tmp.trj nobox\n')
            ftraj.write('EOF\n')
            ftraj.close()
            os.system('chmod u+rwx Run_ptraj; ./Run_ptraj')
            # remove residues from topology files and charged terminals
            '''
            ftraj = open('Run_ptraj', 'w')
            ftraj.write('%s/exe/ptraj prot.top &lt;&lt; EOF\n' % (amber_dir))
            ftraj.write('trajin %s\n' % d_mmpbsa_source.file_trj)
            for i in list_remove_residues:
                ftraj.write('strip :%s\n' % i)
            ftraj.write('strip @H2,H3,OXT &amp; !:WAT\n')
            ftraj.write('trajout md_tmp_noTermCharge.trj nobox\n')
            ftraj.write('EOF\n')
            ftraj.close()
            os.system('chmod u+rwx Run_ptraj; ./Run_ptraj')
            ''' 

        
        # Renumber PDB file
        RenumberPDBFile('prot_lig.pdb')
        RenumberPDBFile('prot_lig_wat.pdb')

        # water's atom number
        fpdb = open('prot_lig_wat.pdb')
        for line in fpdb:
            if line[17:20] == 'WAT' or line[17:20] == 'SOL' or line[17:20] == 'HOH':
                water_atnumb = int(line[4:11])
                break
        fpdb.close()

        # generate topologies
        # ligand only
        fout = open('leapP_lig_only.in','w')
        fout.write('source leaprc.gaff\n')
        fout.write('source leaprc.ff03\n')
        fout.write('loadoff %s.lib\n' % (lig_name))
        fout.write('flig = loadamberparams %s.frcmod\n' % (lig_name))
        fout.write('prot = loadpdb lig_only.pdb\n')
        fout.write('saveoff prot lig_only.lib\n')
        fout.write('saveamberparm prot lig_only.top lig_only.trj\n')
        fout.write('quit\n')
        fout.close()
        
        # protein only
        datalist = []
        for line in open('prot_out.pdb'):
#            if line[13:16] != 'H1 ' and line[13:16] != 'H2 ' and line[13:16] != 'H3 ' and line[13:16] != 'OXT':
            datalist.append(line)
        fout = open('prot_only.pdb', 'w')
        fout.writelines(datalist)
        fout.close()
        RenumberPDBFile('prot_only.pdb')

        # write leapP_prot_only.in
        fout = open('leapP_prot_only.in','w')
        fout.write('source leaprc.gaff\n')
        fout.write('source leaprc.ff03\n')
        ci = 0
        for j in non_prot_res_list_amber:
            if d_mmpbsa_ligands.handle_ligand[ci] == 'prot':
                fout.write('loadoff %s.lib\n' % (j))
                fout.write('fpro = loadamberparams %s.frcmod\n' % (j))
            ci += 1
        for j in cof_flag:
            fout.write('loadoff %s.lib\n' % (filename_cofactors[j]))
            fout.write('fcof = loadamberparams %s.frcmod\n' % (filename_cofactors[j]))
        fout.write('prot = loadpdb prot_only.pdb\n')
        # read first residue number in prot_out.pdb file for proper disulfide numbering
        for line in open('prot_only.pdb'):
            if line.find('ATOM') &gt;= 0:
                resid_zero = int(line[22:26].strip())
                print 'resid_zero %d' % resid_zero
                break
        # add disulfide bridges
        for ds1_c, ds1_i, ds1_n, ds2_c, ds2_i, ds2_n in zip(stored.ds1_chain, stored.ds1_resi, stored.ds1_resn, stored.ds2_chain, stored.ds2_resi, stored.ds2_resn):  
                cr1 = 1 
                for c, i, n in zip(stored.chain, stored.resid, stored.resnam):
                        if ds1_c == c and ds1_i == i and ds1_n == n:
                                res_ds1 = cr1 + int(stored.resid[0]) - 1  
                        cr1 = cr1 + 1    
                cr2 = 1 
                for c, i, n in zip(stored.chain, stored.resid, stored.resnam):
                        if ds2_c == c and ds2_i == i and ds2_n == n: 
                                res_ds2 = cr2 + int(stored.resid[0]) - 1 
                        cr2 = cr2 + 1   
                if ds1_n == 'CYX' and ds2_n == 'CYX':
                    fout.write('bond prot.%d.SG prot.%d.SG\n' % (res_ds1, res_ds2))
                elif ds1_n == 'CY1' and (ds2_n == 'HEM' or ds2_n == 'HEO'):
                    fout.write('bond prot.%d.SG prot.%d.FE\n' % (res_ds1, res_ds2))
                elif (ds1_n == 'HEM' or ds1_n == 'HEO') and ds2_n == 'CY1':
                    fout.write('bond prot.%d.FE prot.%d.SG\n' % (res_ds1, res_ds2))
        fout.write('saveoff prot prot_only.lib\n')
        fout.write('saveamberparm prot prot_only.top prot_only.trj\n')
        fout.write('quit\n')
        fout.close()

        # protein and ligand
	fout = open('leapP.in','w')
	fout.write('source leaprc.gaff\n')
	fout.write('source leaprc.ff03\n')
        ci = 0
        for j in non_prot_res_list_amber:
            if d_mmpbsa_ligands.handle_ligand[ci] == 'prot':
                fout.write('loadoff %s.lib\n' % (j))
                fout.write('fpro = loadamberparams %s.frcmod\n' % (j))
            elif d_mmpbsa_ligands.handle_ligand[ci] == 'lig':
                fout.write('loadoff %s.lib\n' % (j))
                fout.write('flig = loadamberparams %s.frcmod\n' % (j))
            ci += 1
        for j in cof_flag:
            fout.write('loadoff %s.lib\n' % (filename_cofactors[j]))
            fout.write('fcof = loadamberparams %s.frcmod\n' % (filename_cofactors[j]))
	fout.write('prot = loadpdb prot_lig.pdb\n')
        # add disulfide bridges
	for ds1_c, ds1_i, ds1_n, ds2_c, ds2_i, ds2_n in zip(stored.ds1_chain, stored.ds1_resi, stored.ds1_resn, stored.ds2_chain, stored.ds2_resi, stored.ds2_resn):  
		cr1 = 1 
		for c, i, n in zip(stored.chain, stored.resid, stored.resnam):
			if ds1_c == c and ds1_i == i and ds1_n == n:
				res_ds1 = cr1  
			cr1 = cr1 + 1    
		cr2 = 1 
		for c, i, n in zip(stored.chain, stored.resid, stored.resnam):
			if ds2_c == c and ds2_i == i and ds2_n == n: 
				res_ds2 = cr2  
			cr2 = cr2 + 1    
                if ds1_n == 'CYX' and ds2_n == 'CYX':
                    fout.write('bond prot.%d.SG prot.%d.SG\n' % (res_ds1+1, res_ds2+1))
                elif ds1_n == 'CY1' and (ds2_n == 'HEM' or ds2_n == 'HEO'):
                    fout.write('bond prot.%d.SG prot.%d.FE\n' % (res_ds1+1, res_ds2+1))
                elif (ds1_n == 'HEM' or ds1_n == 'HEO') and ds2_n == 'CY1':
                    fout.write('bond prot.%d.FE prot.%d.SG\n' % (res_ds1+1, res_ds2+1))
	fout.write('saveoff prot prot_lig.lib\n')
	fout.write('saveamberparm prot prot_lig.top prot_lig.trj\n')
	fout.write('quit\n')
	fout.close()
        
	# run tleap on complex
        fcom = open('RunCommands', 'w')
        fcom.write('dos2unix *\n')
        fcom.write('%s/exe/tleap -f leapP.in\n' % (amber_dir))
        fcom.write('%s/exe/tleap -f leapP_prot_only.in\n' % (amber_dir))
        fcom.write('%s/exe/tleap -f leapP_lig_only.in\n' % (amber_dir))
        fcom.close()
                
        os.system('mkdir %s' % (mmpbsa_proj_dir))
        os.system('cp prot_lig.pdb prot_only.pdb lig_only.pdb *.lib *.frcmod leapP*in RunCommands ./%s/' % (mmpbsa_proj_dir))
	os.system('cd ./%s; chmod u+rwx RunCommands; ./RunCommands' % (mmpbsa_proj_dir))
	os.system('cp ./%s/*.top .' % (mmpbsa_proj_dir))

                
                
        

        # MMPBSA
        # determine protein-ligand potential energy
        ftop = open('prot_lig.top', 'r')
        ftop.seek(0)
        while ftop:
            line = ftop.readline()
            if line.find('FLAG POINTERS') &gt; -1:
                ftop.readline()
                line = ftop.readline()
                break
        end_protein = int(line[0:8])
        
        ftop.seek(0)
        while ftop:
            line = ftop.readline()
            if line.find('FLAG RESIDUE_POINTER') &gt; -1:
                ftop.readline()
                line = ftop.readline()
                break
        start_lig_id = int(line[0:8])
        end_lig_id = int(line[8:16])-1
        
        ftop.close()
        
        # write mmbpsa_snap.in file
        fmmpbsa = open('mmpbsa_snap.in', 'w')
        fmmpbsa.write('#############################\n')
        fmmpbsa.write('@GENERAL\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('PREFIX                snapshot\n')
        fmmpbsa.write('PATH                  ./\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('COMPLEX               1\n')
        fmmpbsa.write('RECEPTOR              1\n')
        fmmpbsa.write('LIGAND                1\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('COMPT                 ./prot_lig.top\n')
        fmmpbsa.write('RECPT                 ./prot_only.top\n')
        fmmpbsa.write('LIGPT                 ./lig_only.top\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('GC                    1\n')
        fmmpbsa.write('AS                    0\n')
        fmmpbsa.write('DC                    0\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('MM                    0\n')
        fmmpbsa.write('GB                    0\n')
        fmmpbsa.write('PB                    0\n')
        fmmpbsa.write('MS                    0\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('NM                    0\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('################################################################################\n')
        fmmpbsa.write('@MAKECRD\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('BOX                   NO\n')
        fmmpbsa.write('NTOTAL                %d\n' % (nn2))
        fmmpbsa.write('NSTART                %d\n' % d_mmpbsa_frames.start_frame)
        fmmpbsa.write('NSTOP                 %d\n' % d_mmpbsa_frames.end_frame)
        fmmpbsa.write('NFREQ                 %d\n' % d_mmpbsa_frames.interval)
        fmmpbsa.write('#\n')
        fmmpbsa.write('NUMBER_LIG_GROUPS     1\n')
        fmmpbsa.write('LSTART                %d\n' % (start_lig_id))
        fmmpbsa.write('LSTOP                 %d\n' % (end_lig_id))
        fmmpbsa.write('NUMBER_REC_GROUPS     1\n')
        fmmpbsa.write('RSTART                %d\n' % (end_lig_id+1))
        fmmpbsa.write('RSTOP                 %d\n' % (end_protein))
        fmmpbsa.write('#\n')
        fmmpbsa.write('#################################################################################\n')
        fmmpbsa.write('@TRAJECTORY\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('TRAJECTORY            ./md_tmp.trj\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('################################################################################\n')
        fmmpbsa.write('@PROGRAMS\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('################################################################################\n')
        fmmpbsa.close()

        # write mmbpsa_dg.in file
        fmmpbsa = open('mmpbsa_dg.in', 'w')
        fmmpbsa.write('#############################\n')
        fmmpbsa.write('@GENERAL\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('PREFIX                snapshot\n')
        fmmpbsa.write('PATH                  ./\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('COMPLEX               1\n')
        fmmpbsa.write('RECEPTOR              1\n')
        fmmpbsa.write('LIGAND                1\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('COMPT                 ./prot_lig.top\n')
        fmmpbsa.write('RECPT                 ./prot_only.top\n')
        fmmpbsa.write('LIGPT                 ./lig_only.top\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('GC                    0\n')
        fmmpbsa.write('AS                    0\n')
        fmmpbsa.write('DC                    0\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('MM                    1\n')
        fmmpbsa.write('GB                    0\n')
        fmmpbsa.write('PB                    1\n')
        fmmpbsa.write('MS                    1\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('NM                    0\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('################################################################################\n')
        fmmpbsa.write('@PB\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('PROC                  2\n')
        fmmpbsa.write('REFE                  0\n')
        fmmpbsa.write('INDI                  1.0\n')
        fmmpbsa.write('EXDI                  80.0\n')
        fmmpbsa.write('SCALE                 2\n')
        fmmpbsa.write('LINIT                 1000\n')
        fmmpbsa.write('PRBRAD                1.4\n')
        fmmpbsa.write('ISTRNG                0.0\n')
        fmmpbsa.write('RADIOPT               0\n')
        fmmpbsa.write('NPOPT                 1\n')
        fmmpbsa.write('CAVITY_SURFTEN        0.0072\n')
        fmmpbsa.write('CAVITY_OFFSET         0.00\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('SURFTEN               0.0072\n')
        fmmpbsa.write('SURFOFF               0.00\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('################################################################################\n')
        fmmpbsa.write('@MM\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('DIELC                 1.0\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('################################################################################\n')
        fmmpbsa.write('@MS\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('# Molsurf parameters (this section is only relevant if MS = 1 above)\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('#   PROBE - Radius of the probe sphere used to calculate the SAS.\n')
        fmmpbsa.write('#           Since Bondi radii are already augmented by 1.4A, PROBE should be 0.0\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('PROBE                 0.0\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('#################################################################################\n')
        fmmpbsa.write('@PROGRAMS\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('################################################################################\n')
        fmmpbsa.close()

        # Entropy component (based on J Comput Aided Mol Des (2009) 23, 63-71)
        # read protein-ligand pdb file (starting configuration) and extract active (8A) and buffer (12A + water) zone
        prot_list = 'ALA+ARG+ASH+ASN+ASP+CYS+CYX+CY1+GLH+GLN+GLU+GLY+HIS+HIE+HID+HIP+ILE+LEU+LYS+MET+PHE+PRO+SER+THR+TRP+TYR+VAL'
        prot_wat_list = 'ALA+ARG+ASH+ASN+ASP+CYS+CYX+CY1+GLH+GLN+GLU+GLY+HIS+HIE+HID+HIP+ILE+LEU+LYS+MET+PHE+PRO+SER+THR+TRP+TYR+VAL+HOH+WAT+SOL'
        wat_list = 'HOH+WAT+SOL'
            
        # protein list + co-factors
        ci = 0
        for j in non_prot_res_list_amber:
            if d_mmpbsa_ligands.handle_ligand[ci] == 'prot':
                tmp_list = '%s+%s' % (prot_list, j)
                prot_list = tmp_list
                tmp_list = '%s+%s' % (prot_wat_list, j)
                prot_wat_list = tmp_list
            ci += 1
            
        # protein list + co-factors + ligand
        prot_lig_list  = prot_list
        prot_lig_wat_list = prot_wat_list
        ci = 0
        for j in non_prot_res_list_amber:
            if d_mmpbsa_ligands.handle_ligand[ci] == 'lig':
                tmp_list = '%s+%s' % (prot_lig_list, j)
                prot_lig_list = tmp_list
                tmp_list = '%s+%s' % (prot_lig_wat_list, j)
                prot_lig_wat_list = tmp_list
            ci += 1
                

        for na in cmd.get_names('objects'):
            cmd.remove(na)
            cmd.delete(na)
        cmd.load('prot_lig_wat.pdb')
	for na in cmd.get_names('objects'):
            try:
                cmd.select('pro', na)
#                cmd.select('pro2', 'pro and resn %s' % prot_list)               # protein
                cmd.select('pro3', 'pro and ((resn %s and (not name H1+H2+OXT)) or resn %s)' % (prot_list, wat_list))           # protein + water
#                cmd.select('pro2a', 'pro and resn %s' % prot_lig_list)          # protein + ligand
                cmd.select('pro3a', 'pro and ((resn %s and (not name H1+H2+OXT)) or resn %s)' % (prot_lig_list, wat_list))      # protein + water + ligand
#                cmd.select('pro10', 'pro and resn %s' % wat_list)               # water
            
                cmd.select('pro4', 'pro and resn %s' % lig_name)                # ligand
                
                cmd.select('pro_12', 'pro3 and byres (pro4 around 12)')
                cmd.select('pro_lig_12', 'pro3a and byres (pro4 around 12) or pro4')
#                cmd.select('wat_12', 'pro10 and byres (pro4 around 12)')
#                cmd.select('pro_8', 'pro2 and byres (pro4 around 8)')
#                cmd.select('pro_lig_8', 'pro2a and byres (pro4 around 8) or pro4')
                
                stored.ID12 = []
                stored.ID12pl = []
                L = cmd.count_atoms('pro_lig_12')
                print L
                if L &gt; 0:
                    cmd.save('prot_lig_12.pdb', 'pro_lig_12', 0, 'pdb')
                    ResortPDB4Amber_removeChargedTerminal('prot_lig_12.pdb')
                    cmd.iterate ('pro_lig_12', 'stored.ID12pl.append(ID)')
#                    print stored.ID12pl
#                    print 'aaa1'
                    

                    stored.chain12pl = []
                    stored.resnam12pl = []
                    stored.resid12pl = []
                    cmd.select('sele12pl', 'pro_lig_12 and (name CA+FE or id 1)')
                    cmd.iterate('sele12pl', 'stored.chain12pl.append(chain)')
                    cmd.iterate('sele12pl', 'stored.resnam12pl.append(resn)')
                    cmd.iterate('sele12pl', 'stored.resid12pl.append(resi)')
#                    print 'aaa2'
#                    print stored.resid12pl

                L = cmd.count_atoms('pro_12')
                print L
                if L &gt; 0:
                    cmd.save('prot_12.pdb', 'pro_12', 0, 'pdb')
                    ResortPDB4Amber_removeChargedTerminal('prot_12.pdb')
                    cmd.iterate ('pro_12', 'stored.ID12.append(ID)')
#                    print 'bbb1'
#                    print stored.ID12

                    stored.chain12 = []
                    stored.resnam12 = []
                    stored.resid12 = []
                    cmd.select('sele12', 'pro_12 and name CA+FE')
                    cmd.iterate('sele12', 'stored.chain12.append(chain)')
                    cmd.iterate('sele12', 'stored.resnam12.append(resn)')
                    cmd.iterate('sele12', 'stored.resid12.append(resi)')
#                    print 'bbb2'
#                    print stored.resid12
        
                    
#                L = cmd.count_atoms('pro_8')
#                print L
#                if L &gt; 0:
#                    cmd.save('prot_8.pdb', 'pro_8', 0, 'pdb')
#                    ResortPDB4Amber('prot_8.pdb')

#                L = cmd.count_atoms('wat_12')
#                L_wat_12 = L/3
#                print L_wat_12

            except:
                pass
        
        # generate list of receptor groups for MMPBSA module of amber
        startid = [0 for i in range(1000)]
        stopid = [0 for i in range(1000)]
        ci = 0
        oldid = -99999
        for i in stored.ID12:
            if int(i) != oldid + 1:
                startid[ci] = int(i)
                if ci &gt; 0:
                    stopid[ci-1] = oldid
                ci += 1
            oldid = int(i)
        stopid[ci-1] = oldid
        
        fout = open('reclist.txt', 'w')
        fout.write('NUMBER_REC_GROUPS  % 7d\n' % ci)
        for i in range(ci):
            fout.write('RSTART             % 7d\n' % startid[i])
            fout.write('RSTOP              % 7d\n' % stopid[i])
        fout.close()
            
        # write out mm_pbsa_nm.in file for NMODE
        # write mmbpsa_snap.in file
        fmmpbsa = open('mmpbsa_nm.in', 'w')
        fmmpbsa.write('#############################\n')
        fmmpbsa.write('@GENERAL\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('PREFIX                md_12\n')
        fmmpbsa.write('PATH                  ./\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('COMPLEX               1\n')
        fmmpbsa.write('RECEPTOR              1\n')
        fmmpbsa.write('LIGAND                1\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('COMPT                 ./prot_lig_12.top\n')
        fmmpbsa.write('RECPT                 ./prot_12.top\n')
        fmmpbsa.write('LIGPT                 ./lig_only.top\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('GC                    0\n')
        fmmpbsa.write('AS                    0\n')
        fmmpbsa.write('DC                    0\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('MM                    0\n')
        fmmpbsa.write('GB                    0\n')
        fmmpbsa.write('PB                    0\n')
        fmmpbsa.write('MS                    0\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('NM                    1\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('################################################################################\n')
        fmmpbsa.write('@MAKECRD\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('BOX                   YES\n')
        fmmpbsa.write('NTOTAL                %d\n' % (nn2))
        fmmpbsa.write('NSTART                %d\n' % d_mmpbsa_frames.start_frame)
        fmmpbsa.write('NSTOP                 %d\n' % d_mmpbsa_frames.end_frame)
        fmmpbsa.write('NFREQ                 %d\n' % d_mmpbsa_frames.interval_entropy)
        fmmpbsa.write('#\n')
        fmmpbsa.write('NUMBER_LIG_GROUPS     1\n')
        fmmpbsa.write('LSTART                %d\n' % (start_lig_id))
        fmmpbsa.write('LSTOP                 %d\n' % (end_lig_id))
        for j in open('reclist.txt', 'r'):
            fmmpbsa.write(j)
        fmmpbsa.write('#\n')
        fmmpbsa.write('#################################################################################\n')
        fmmpbsa.write('@TRAJECTORY\n')
        fmmpbsa.write('#\n')
#        fmmpbsa.write('TRAJECTORY            ./md_tmp_noTermCharge.trj\n')
        fmmpbsa.write('TRAJECTORY            ./md_tmp.trj\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('#################################################################################\n')
        fmmpbsa.write('@NM\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('DIELC                 1\n')
        fmmpbsa.write('MAXCYC                1000\n')
        fmmpbsa.write('DRMS                  0.1\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('################################################################################\n')
        fmmpbsa.write('@PROGRAMS\n')
        fmmpbsa.write('#\n')
        fmmpbsa.write('################################################################################\n')
        fmmpbsa.close()
        
        # write script for changepdb
        fchangepdb = open('Run_changepdb', 'w')
        fchangepdb.write('%s/changepdb &lt;&lt; EOF\n' % changepdb_dir)
        fchangepdb.write('prot_lig_12.pdb\n')
        fchangepdb.write('ren\n')
        fchangepdb.write('\n')
        fchangepdb.write('fix\n')
        fchangepdb.write('temp2\n')
        fchangepdb.write('c\n')
        fchangepdb.write('n\n')
        fchangepdb.write('y\n')
        fchangepdb.write('\n')
        fchangepdb.write('\n')
        fchangepdb.write('%s\n' % (lig_name))
        fchangepdb.write('8\n')
        fchangepdb.write('n\n')
        fchangepdb.write('y\n')
        fchangepdb.write('temp2.pdb\n')
        fchangepdb.write('y\n')
        fchangepdb.write('n\n')
        fchangepdb.write('q\n')
        fchangepdb.write('EOF\n')
        fchangepdb.close()

        # write script for changecrd
        fchangecrd = open('Run_changecrd', 'w')
        fchangecrd.write('%s/changecrd &lt;&lt; EOF\n' % changecrd_dir)
        fchangecrd.write('%d\n' % nn2)
        fchangecrd.write('md_tmp.trj\n')
        fchangecrd.write('l\n')
        fchangecrd.write('mmpbsa_nm.in\n')
        fchangecrd.write('n\n')
        fchangecrd.write('%d\n' % water_atnumb)
        fchangecrd.write('3\n')
        fchangecrd.write('0\n')
        fchangecrd.write('q\n')
        fchangecrd.write('EOF\n')
        fchangecrd.close()
                

        # generate topologies for prot_lig_12
        # protein only
        # find disulfide bridges
        find_disulfide_bridges_new('prot_12.pdb')
        # read first residue number in prot_out.pdb file for proper disulfide numbering
        for line in open('prot_12.pdb'):
            if line.find('ATOM') &gt;= 0:
                resid_zero = int(line[22:26].strip())
                break
    
        # write leapP_prot_only.in
        fout = open('leapP_prot_only.in','w')
        fout.write('source leaprc.gaff\n')
        fout.write('source leaprc_noTER.ff03\n')
        ci = 0
        for j in non_prot_res_list_amber:
            if d_mmpbsa_ligands.handle_ligand[ci] == 'prot':
                fout.write('loadoff %s.lib\n' % (j))
                fout.write('fpro = loadamberparams %s.frcmod\n' % (j))
            ci += 1
        for j in cof_flag:
            fout.write('loadoff %s.lib\n' % (filename_cofactors[j]))
            fout.write('fcof = loadamberparams %s.frcmod\n' % (filename_cofactors[j]))
        fout.write('prot = loadpdb prot_12.pdb\n')
        # add disulfide bridges
        for ds1_i, ds1_n, ds2_i, ds2_n in zip(disulfide_A, disulfide_A_name, disulfide_B, disulfide_B_name):
            if (ds1_n == 'CYX' or ds1_n == 'CYS') and (ds2_n == 'CYX' or ds2_n == 'CYS'):
                fout.write('bond prot.%d.SG prot.%d.SG\n' % (int(ds1_i)+resid_zero-1, int(ds2_i)+resid_zero-1))
            elif (ds1_n == 'CY1' or ds1_n == 'CYS') and (ds2_n == 'HEM' or ds2_n == 'HEO'):
                fout.write('bond prot.%d.SG prot.%d.FE\n' % (int(ds1_i)+resid_zero-1, int(ds2_i)+resid_zero-1))
            elif (ds1_n == 'HEM' or ds1_n == 'HEO') and (ds2_n == 'CY1' or ds2_n == 'CYS'):
                fout.write('bond prot.%d.FE prot.%d.SG\n' % (int(ds1_i)+resid_zero-1, int(ds2_i)+resid_zero-1))
        fout.write('saveoff prot prot_12.lib\n')
        fout.write('saveamberparm prot prot_12.top prot_12.trj\n')
        fout.write('quit\n')
        fout.close()

        # protein and ligand
        # find disulfide bridges
        find_disulfide_bridges_new('prot_lig_12.pdb')
#        print disulfide_A, disulfide_B, disulfide_A_name, disulfide_B_name
        # read first residue number in prot_out.pdb file for proper disulfide numbering
        for line in open('prot_lig_12.pdb'):
            if line.find('ATOM') &gt;= 0:
                resid_zero = int(line[22:26].strip())
                break
        # write leapP.in
	fout = open('leapP.in','w')
	fout.write('source leaprc.gaff\n')
	fout.write('source leaprc_noTER.ff03\n')
        ci = 0
        for j in non_prot_res_list_amber:
            if d_mmpbsa_ligands.handle_ligand[ci] == 'prot':
                fout.write('loadoff %s.lib\n' % (j))
                fout.write('fpro = loadamberparams %s.frcmod\n' % (j))
            elif d_mmpbsa_ligands.handle_ligand[ci] == 'lig':
                fout.write('loadoff %s.lib\n' % (j))
                fout.write('flig = loadamberparams %s.frcmod\n' % (j))
            ci += 1
        for j in cof_flag:
            fout.write('loadoff %s.lib\n' % (filename_cofactors[j]))
            fout.write('fcof = loadamberparams %s.frcmod\n' % (filename_cofactors[j]))
	fout.write('prot = loadpdb prot_lig_12.pdb\n')
        # add disulfide bridges
        for ds1_i, ds1_n, ds2_i, ds2_n in zip(disulfide_A, disulfide_A_name, disulfide_B, disulfide_B_name):
            if (ds1_n == 'CYX' or ds1_n == 'CYS') and (ds2_n == 'CYX' or ds2_n == 'CYS'):
                fout.write('bond prot.%d.SG prot.%d.SG\n' % (int(ds1_i)+resid_zero-1, int(ds2_i)+resid_zero-1))
            elif (ds1_n == 'CY1' or ds1_n == 'CYS') and (ds2_n == 'HEM' or ds2_n == 'HEO'):
                fout.write('bond prot.%d.SG prot.%d.FE\n' % (int(ds1_i)+resid_zero-1, int(ds2_i)+resid_zero-1))
            elif (ds1_n == 'HEM' or ds1_n == 'HEO') and (ds2_n == 'CY1' or ds2_n == 'CYS'):
                fout.write('bond prot.%d.FE prot.%d.SG\n' % (int(ds1_i)+resid_zero-1, int(ds2_i)+resid_zero-1))
	fout.write('saveoff prot prot_lig_12.lib\n')
	fout.write('saveamberparm prot prot_lig_12.top prot_lig_12.trj\n')
	fout.write('quit\n')
	fout.close()
        
	# run tleap on complex
        fcom = open('RunCommands', 'w')
        fcom.write('dos2unix *\n')
        fcom.write('%s/exe/tleap -f leapP.in\n' % (amber_dir))
        fcom.write('%s/exe/tleap -f leapP_prot_only.in\n' % (amber_dir))
        fcom.close()
                
#        os.system('cp prot_lig_12.pdb prot_12.pdb *.lib *.frcmod leapP*in md_tmp.trj md_tmp_noTermCharge.trj mmpbsa*.in RunCommands Run_changepdb Run_changecrd ./%s/' % (mmpbsa_proj_dir))
        os.system('cp prot_lig_12.pdb prot_12.pdb *.lib *.frcmod leapP*in md_tmp.trj mmpbsa*.in RunCommands Run_changepdb Run_changecrd ./%s/' % (mmpbsa_proj_dir))
	os.system('cd ./%s; chmod u+rwx RunCommands; chmod u+rwx Run_changepdb; chmod u+rwx Run_changecrd; ./RunCommands; ./Run_changepdb; ./Run_changecrd' % (mmpbsa_proj_dir))
	os.system('cp ./%s/*.top ./%s/temp2 .' % (mmpbsa_proj_dir, mmpbsa_proj_dir))
#        return 0
	# remove ligand from temp2 --&gt; temp2nl
	cline = 0
	ftemp2nl = open('temp2nl', 'w')
	for line in open('temp2'):
		if cline &gt; 0:
			ftemp2nl.write(line)
		cline = cline + 1
	ftemp2nl.close()
        
        
	# copy mm_pbsa_loc from amber_dir to local directory
	fcom = open('RunMMPBSA', 'w')
	fcom.write('mm_pbsa.pl mmpbsa_snap.in &gt; mmpbsa_snap.log\n')
	fcom.write('mm_pbsa.pl mmpbsa_dg.in &gt; mmpbsa_dg.log\n')
	fcom.write('cp %s/exe/mm_pbsa_loc.pl .\n' % amber_dir)
	fcom.write('cp %s/src/mm_pbsa/mm_pbsa_loc_createinput_part*.pm .\n' % amber_dir)
	fcom.write('cat mm_pbsa_loc_createinput_part1.pm temp2 mm_pbsa_loc_createinput_part2.pm temp2 mm_pbsa_loc_createinput_part3.pm temp2nl mm_pbsa_loc_createinput_part4.pm temp2nl mm_pbsa_loc_createinput_part5.pm &gt; mm_pbsa_loc_createinput.pm\n')
	fcom.write('./mm_pbsa_loc.pl mmpbsa_nm.in &gt; mmpbsa_nm.log\n')
	fcom.close()
        
        
	os.system('cp RunMMPBSA mmpbsa*.in temp2nl ./%s/' % (mmpbsa_proj_dir))
#        childp = subprocess.Popen('cd ./%s; chmod u+rwx RunMMPBSA; nohup ./RunMMPBSA' % (mmpbsa_proj_dir), shell=True)
        tkMessageBox.showinfo('Preparation of MMPBSA calculation done','Job has been started on server.')
#	os.system('%s %s@%s:%s/%s/snapshot_statistics.out .' % (scp_exe, username, nodename, linux_dir, mmpbsa_proj_dir))

#######################################################################################
def run(program, *args):
	pid = os.fork()
	if not pid:
		os.execvp(program, (program,) + args)
	return os.wait()[0]


#######################################################################################
def RenumberPDBFile(filename):
	fin = open(filename, 'r')
	fout = open('tmp.pdb', 'w') 
        ci = 1
	for line in fin:
		if line[0:6] == 'ATOM  ' or line[0:6] == 'HETATM': 
                    new_line = []
#                    new_line.append(line[0:6])
                    new_line.append('ATOM% 7d' % ci)
                    new_line.append(line[11:])
                    fout.write(''.join(new_line))
                    atomnam = line[12:15]
#                    print atomnam, atomnam.find('OXT')
                    if atomnam.find('OXT') &gt;= 0:
                        fout.write('TER\n')
                    ci += 1
                else:
                    fout.write(line)
		
	fin.close()
	fout.close()

        os.remove('%s' % (filename))
	os.rename('tmp.pdb', '%s' % (filename))	 

#######################################################################################
def ResortPDB4Amber(filename):
	listres = ['ALA', 'ARG', 'ASH', 'ASN', 'ASP', 'CYS', 'CYX', 'CY1', 'GLH', 'GLN', 'GLU', 'GLY', 'HIS', 'HIE', 'HID', 'HIP', 'ILE', 'LEU', 'LYS', 'MET', 'PHE', 'PRO', 'SER', 'THR', 'TRP', 'TYR', 'VAL']
	list_ter_chain = []
	list_ter_id = []
	list_ter_name = []
     
	fin = open(filename, 'r')
	fout = open('tmp.pdb', 'w') 
        
  
	oldresnam = ''
	oldresid = -999
	o_found = 0  
      
	for line in fin:
		resnam = line[17:20]
		flag = 0 
		for s in listres:  
			if resnam.find(s) &gt; -1:
				flag = 1
		if flag == 1:		# only protein residues (+heme, ...)  
			if line[13:15] == 'C ':
				o_x = float(line[30:38])  
				o_y = float(line[38:46])
				o_z = float(line[46:54])
				o_chain = line[21:22]  
				o_id = line[22:27]  
				o_name = line[17:20]  
				o_found = 1
				n_found = 0  
			if line[13:15] == 'N ':
				n_x = float(line[30:38])  
				n_y = float(line[38:46])
				n_z = float(line[46:54])
				n_found = 1
			if o_found == 1 and n_found == 1:
#                                print '%s %f' % (resnam, math.sqrt(math.pow(o_x - n_x, 2) + math.pow(o_y - n_y, 2) + math.pow(o_z - n_z, 2)))
				if(math.sqrt(math.pow(o_x - n_x, 2) + math.pow(o_y - n_y, 2) + math.pow(o_z - n_z, 2)) &gt; 3.0):		# check distance between C and N
                                    list_ter_chain.append(o_chain)
                                    list_ter_id.append(o_id)
                                    list_ter_name.append(o_name)
                                o_found = 0
                                n_found = 0 
	if o_found == 1 and n_found == 0:		# final residue
		list_ter_chain.append(o_chain)
		list_ter_id.append(o_id)
		list_ter_name.append(o_name)
	fin.close()       

	fin = open(filename, 'r')
	old_chain = ' '
	old_idd = '-999'
	old_name = 'YYY'
	flag_ter = 0   
	for line in fin:
		if line[0:6] == 'ATOM  ' or line[0:6] == 'HETATM': 
			chain = line[21:22]
			idd = line[22:27]
			resnam = line[17:20]
			if chain != old_chain or idd != old_idd or resnam != old_resnam:
				if flag_ter == 1:
					fout.write('TER\n')  
					flag_ter = 0 
				flag = 0 
				for s in listres:  
					if resnam.find(s) &gt; -1:
						flag = 1
				if flag == 1:		# only protein residues
					for o_chain, o_id, o_name in zip(list_ter_chain, list_ter_id, list_ter_name):
						if chain == o_chain and idd == o_id and resnam == o_name:
							flag_ter = 1
                                else:                   # cofactors, effectors etc.
                                        flag_ter = 1
			old_chain = chain
			old_idd = idd
			old_resnam = resnam  
			  
			fout.write(line)  
		
	fin.close()
	fout.close()

        os.remove('%s' % (filename))
	os.rename('tmp.pdb', '%s' % (filename))	 
 

#######################################################################################
def ResortPDB4Amber_removeChargedTerminal(filename):
	listres = ['ALA', 'ARG', 'ASH', 'ASN', 'ASP', 'CYS', 'CYX', 'CY1', 'GLH', 'GLN', 'GLU', 'GLY', 'HIS', 'HIE', 'HID', 'HIP', 'ILE', 'LEU', 'LYS', 'MET', 'PHE', 'PRO', 'SER', 'THR', 'TRP', 'TYR', 'VAL']
	list_ter_chain = []
	list_ter_id = []
	list_ter_name = []
     
	fin = open(filename, 'r')
	fout = open('tmp.pdb', 'w') 
        
  
	oldresnam = ''
	oldresid = -999
	o_found = 0  
      
	for line in fin:
		resnam = line[17:20]
		flag = 0 
		for s in listres:  
			if resnam.find(s) &gt; -1:
				flag = 1
		if flag == 1:		# only protein residues (+heme, ...)  
			if line[13:15] == 'C ':
				o_x = float(line[30:38])  
				o_y = float(line[38:46])
				o_z = float(line[46:54])
				o_chain = line[21:22]  
				o_id = line[22:27]  
				o_name = line[17:20]  
				o_found = 1
				n_found = 0  
			if line[13:15] == 'N ':
				n_x = float(line[30:38])  
				n_y = float(line[38:46])
				n_z = float(line[46:54])
				n_found = 1
			if o_found == 1 and n_found == 1:
#                                print '%s %f' % (resnam, math.sqrt(math.pow(o_x - n_x, 2) + math.pow(o_y - n_y, 2) + math.pow(o_z - n_z, 2)))
				if(math.sqrt(math.pow(o_x - n_x, 2) + math.pow(o_y - n_y, 2) + math.pow(o_z - n_z, 2)) &gt; 3.0):		# check distance between C and N
                                    list_ter_chain.append(o_chain)
                                    list_ter_id.append(o_id)
                                    list_ter_name.append(o_name)
                                o_found = 0
                                n_found = 0 
	if o_found == 1 and n_found == 0:		# final residue
		list_ter_chain.append(o_chain)
		list_ter_id.append(o_id)
		list_ter_name.append(o_name)
	fin.close()       

	fin = open(filename, 'r')
	old_chain = ' '
	old_idd = '-999'
	old_name = 'YYY'
	flag_ter = 0   
	for line in fin:
		if line[0:6] == 'ATOM  ' or line[0:6] == 'HETATM': 
                    if line[17:20] == 'WAT' or line[17:20] == 'SOL' or line[17:20] == 'HOH' or (line[13:16] != 'H1 ' and line[13:16] != 'H2 ' and line[13:16] != 'H3 ' and line[13:16] != 'OXT'):

			chain = line[21:22]
			idd = line[22:27]
			resnam = line[17:20]
			if chain != old_chain or idd != old_idd or resnam != old_resnam:
				if flag_ter == 1:
					fout.write('TER\n')  
					flag_ter = 0 
				flag = 0 
				for s in listres:  
					if resnam.find(s) &gt; -1:
						flag = 1
				if flag == 1:		# only protein residues
					for o_chain, o_id, o_name in zip(list_ter_chain, list_ter_id, list_ter_name):
						if chain == o_chain and idd == o_id and resnam == o_name:
							flag_ter = 1
                                else:                   # cofactors, effectors etc.
                                        flag_ter = 1
			old_chain = chain
			old_idd = idd
			old_resnam = resnam  
			  
			fout.write(line)  
		
	fin.close()
	fout.close()

        os.remove('%s' % (filename))
	os.rename('tmp.pdb', '%s' % (filename))	 
 

#######################################################################################
def find_disulfide_bridges_2(filename, cof_flag, ligname):
        global disulfide_A
        global disulfide_B
        global disulfide_A_name
        global disulfide_B_name
        global disulfide_A_atom
        global disulfide_B_atom
        
        disulfide_A = []
        disulfide_B = []
        disulfide_A_name = []
        disulfide_B_name = []
        disulfide_A_atom = []
        disulfide_B_atom = []
        
        tmp_store_x = []
        tmp_store_y = []
        tmp_store_z = []
        tmp_store_id = []
        tmp_store_name = []
        tmp_store_atom = []
        
        # write temporary tleap input file and run tleap to generate temporary pdb file for identifying disulfide bonds
        fout = open('tmp_leap.in', 'w') 
        fout.write('source leaprc.gaff\n')
        fout.write('source leaprc.ff03\n')
#        fout.write('source leaprc_noTER.ff03\n')
        for j in cof_flag:
            os.system('cp %s/%s.lib %s/%s.frcmod .' % (library_dir, filename_cofactors[j], library_dir, filename_cofactors[j]))
            fout.write('loadoff %s.lib\n' % (filename_cofactors[j]))
            fout.write('fcof = loadamberparams %s.frcmod\n' % (filename_cofactors[j]))
        fout.write('prot = loadpdb %s\n' % filename)
        fout.write('savepdb prot tmp_pdb.pdb\n')
        fout.write('quit\n')
        fout.close()
        
        os.system('%s/exe/tleap -f tmp_leap.in\n' % (amber_dir))
        
        # read in temporary pdb file and identify residue numbers of disulfide bridges
        fin = open('tmp_pdb.pdb', 'r')
      
        for line in fin:
            resnam = line[17:20]
            atmnam2 = line[12:15]
            atmnam = atmnam2.strip()
            flag = 0
            for i, j in zip(bond_info_res1, bond_info_atm1):
                if resnam == i and atmnam == j:
                    flag = 1 
            for i, j in zip(bond_info_res2, bond_info_atm2):
                if resnam == i and atmnam == j:
                    flag = 1 
            if flag == 1:
                o_x = float(line[30:38])  
                o_y = float(line[38:46])
                o_z = float(line[46:54])
                o_id = line[22:27]  
                
                tmp_store_x.append(o_x)
                tmp_store_y.append(o_y)
                tmp_store_z.append(o_z)
                tmp_store_id.append(o_id)
                tmp_store_name.append(resnam)
                tmp_store_atom.append(atmnam)
        fin.close()
        
        for i1, j1, i2, j2, dd in zip(bond_info_res1, bond_info_atm1, bond_info_res2, bond_info_atm2, bond_info_dist):
            ci = 0
            for o_id in tmp_store_id:
                o_x = tmp_store_x[ci]
                o_y = tmp_store_y[ci]
                o_z = tmp_store_z[ci]
                cj = 0
                for n_id in tmp_store_id:
                    n_x = tmp_store_x[cj]
                    n_y = tmp_store_y[cj]
                    n_z = tmp_store_z[cj]
                    if ci &lt; cj and (
                            (tmp_store_name[ci] == i1 and tmp_store_atom[ci] == j1 and tmp_store_name[cj] == i2 and tmp_store_atom[cj] == j2)
                            or
                            (tmp_store_name[ci] == i2 and tmp_store_atom[ci] == j2 and tmp_store_name[cj] == i1 and tmp_store_atom[cj] == j1)
                            ): 
                        if(math.sqrt(math.pow(o_x - n_x, 2) + math.pow(o_y - n_y, 2) + math.pow(o_z - n_z, 2)) &lt; float(dd)):		# check distance between C and N
                            disulfide_A.append(o_id)
                            disulfide_B.append(n_id)
                            disulfide_A_name.append(tmp_store_name[ci])
                            disulfide_B_name.append(tmp_store_name[cj])
                            disulfide_A_atom.append(tmp_store_atom[ci])
                            disulfide_B_atom.append(tmp_store_atom[cj])
                    cj += 1
                ci += 1

        os.remove('tmp_leap.in')
	os.remove('tmp_pdb.pdb')
        
#        print disulfide_A, disulfide_B, disulfide_A_name, disulfide_B_name, disulfide_A_atom, disulfide_B_atom
#######################################################################################
def find_disulfide_bridges_new(filename):
        global disulfide_A
        global disulfide_B
        global disulfide_A_name
        global disulfide_B_name
        
        disulfide_A = []
        disulfide_B = []
        disulfide_A_name = []
        disulfide_B_name = []
        
        tmp_store_x = []
        tmp_store_y = []
        tmp_store_z = []
        tmp_store_id = []
        tmp_store_name = []
        
        # write temporary tleap input file and run tleap to generate temporary pdb file for identifying disulfide bonds
	fout = open('tmp_leap.in', 'w') 
        fout.write('source leaprc.gaff\n')
        fout.write('source leaprc_noTER.ff03\n')
        ci = 0
        for j in non_prot_res_list_amber:
            if d_mmpbsa_ligands.handle_ligand[ci] == 'prot':
                fout.write('loadoff %s.lib\n' % (j))
                fout.write('fhem = loadamberparams %s.frcmod\n' % (j))
            ci += 1
        fout.write('prot = loadpdb %s\n' % filename)
        fout.write('savepdb prot tmp_pdb.pdb\n')
        fout.write('quit\n')
        fout.close()
        
        os.system('%s/exe/tleap -f tmp_leap.in\n' % (amber_dir))
        
        # read in temporary pdb file and identify residue numbers of disulfide bridges
        fin = open('tmp_pdb.pdb', 'r')
      
	for line in fin:
            resnam = line[17:20]
            atmnam = line[13:15]
            flag = 0 
            if (resnam == 'CYS' or resnam == 'CYX') and atmnam == 'SG':
                o_x = float(line[30:38])  
                o_y = float(line[38:46])
                o_z = float(line[46:54])
                o_id = line[22:27]  
                
                tmp_store_x.append(o_x)
                tmp_store_y.append(o_y)
                tmp_store_z.append(o_z)
                tmp_store_id.append(o_id)
                tmp_store_name.append(resnam)

        ci = 0
        for o_id in tmp_store_id:
            o_x = tmp_store_x[ci]
            o_y = tmp_store_y[ci]
            o_z = tmp_store_z[ci]
            cj = 0
            for n_id in tmp_store_id:
                n_x = tmp_store_x[cj]
                n_y = tmp_store_y[cj]
                n_z = tmp_store_z[cj]
                if ci &lt; cj:
                    if(math.sqrt(math.pow(o_x - n_x, 2) + math.pow(o_y - n_y, 2) + math.pow(o_z - n_z, 2)) &lt; 2.5):		# check distance between C and N
                        disulfide_A.append(o_id)
                        disulfide_B.append(n_id)
                        disulfide_A_name.append(tmp_store_name[ci])
                        disulfide_B_name.append(tmp_store_name[cj])
                cj += 1
            ci += 1

#        os.remove('tmp_leap.in')
#	os.rename('tmp_pdb.pdb')	 
 
#######################################################################################
def find_disulfide_bridges(pro2):
	stored.ds1_chain = []
	stored.ds1_resi = []
	stored.ds1_resn = []
	stored.ds2_chain = []
	stored.ds2_resi = []
	stored.ds2_resn = []
	
	for a in cmd.index('pro2 and (CYS/SG|CYX/SG)'):
		for b in cmd.index('pro2 and (CYS/SG|CYX/SG)'):
			if a[1] &lt; b[1]:
				cmd.select('s1','%s`%d'%a)
				cmd.select('s2','%s`%d'%b)
				if cmd.dist('tmp','s1','s2') &lt; 3:
					cmd.select('res1', 'byres s1') 
					cmd.select('res2', 'byres s2') 
					cmd.alter('res1', 'resn=\'%s\'' % ('CYX'))
					cmd.alter('res2', 'resn=\'%s\'' % ('CYX'))
					cmd.iterate ('s1', 'stored.ds1_chain.append(chain)')
					cmd.iterate ('s1', 'stored.ds1_resi.append(resi)')
					cmd.iterate ('s1', 'stored.ds1_resn.append(resn)')
					cmd.iterate ('s2', 'stored.ds2_chain.append(chain)')
					cmd.iterate ('s2', 'stored.ds2_resi.append(resi)')
					cmd.iterate ('s2', 'stored.ds2_resn.append(resn)')
					cmd.delete('res1')
					cmd.delete('res2')
				cmd.delete('tmp')
				cmd.delete('s1')
				cmd.delete('s2')

	for a in cmd.index('pro2 and (CY*/SG)'):
		for b in cmd.index('pro2 and (HEM/FE|HEO/FE)'):
				cmd.select('s1','%s`%d'%a)
				cmd.select('s2','%s`%d'%b)
				if cmd.dist('tmp','s1','s2') &lt; 3.5:
					cmd.select('res1', 'byres s1') 
					cmd.alter('res1', 'resn=\'%s\'' % ('CY1'))
					cmd.iterate ('s1', 'stored.ds1_chain.append(chain)')
					cmd.iterate ('s1', 'stored.ds1_resi.append(resi)')
					cmd.iterate ('s1', 'stored.ds1_resn.append(resn)')
					cmd.iterate ('s2', 'stored.ds2_chain.append(chain)')
					cmd.iterate ('s2', 'stored.ds2_resi.append(resi)')
					cmd.iterate ('s2', 'stored.ds2_resn.append(resn)')
					cmd.delete('res1')
				cmd.delete('tmp')
				cmd.delete('s1')
				cmd.delete('s2')

#######################################################################################
def CosAngle(v1, v2, v3):
        r21 = [0.0 for i in range(3)]
        r23 = [0.0 for i in range(3)]

        d21 = 0.0
	d23 = 0.0
	for i in range(0, 3):
            r21[i] = v2[i] - v1[i]
            r23[i] = v2[i] - v3[i]
            d21 += pow(r21[i], 2)
            d23 += pow(r23[i], 2)
	scalar = 0.0
	for i in range(0, 3):
            scalar += r21[i]*r23[i];
	scalar /= math.sqrt(d21*d23);

	return scalar;

#######################################################################################
def Distance_Point_Point(a, b):
    return( math.sqrt(math.pow(a[0]-b[0], 2)+math.pow(a[1]-b[1], 2)+math.pow(a[2]-b[2], 2)) )

#######################################################################################
def calculateSolventExposure(a, na):
        x_axis = [0.0 for i in range(3)]
        y_axis = [0.0 for i in range(3)]
        z_axis = [0.0 for i in range(3)]
        direct = [[] for i in range(50)]
        line_z = [0.0 for i in range(3)]
        line_n = [0.0 for i in range(3)]
        end_dir = [0.0 for i in range(3)]

        x_axis[0] = 1.0
        x_axis[1] = 0.0
        x_axis[2] = 0.0
        y_axis[0] = 0.0
        y_axis[1] = 1.0
        y_axis[2] = 0.0
        z_axis[0] = 0.0
        z_axis[1] = 0.0
        z_axis[2] = 1.0

        cmd.select('Calpha', na+' and name CA')

        # Calculate 26 vectors
        ci = 0;
        for jx in range(-1, 2):
            for jy in range(-1, 2):
                for jz in range(-1, 2):
                    if jx != 0 or jy != 0 or jz != 0:
                        direct[ci] = [0.0 for i in range(3)]
                        for k in range(0,3):
                            direct[ci][k] = jx*x_axis[k] + jy*y_axis[k] + jz*z_axis[k]
                        sum = direct[ci][0]*direct[ci][0] + direct[ci][1]*direct[ci][1] + direct[ci][2]*direct[ci][2]
                        sum = math.sqrt(sum)
                        for k in range(0,3):
                            direct[ci][k] /= sum
#                        print 'direct: %d %f %f %f' % (ci, direct[ci][0], direct[ci][1], direct[ci][2])
                        ci += 1

        # Calculate 24 intermediate vectors
        for jx in range(-1, 2, 2):
            for jy in range(-1, 2, 2):
                for jz in range(-1, 2, 2):
                    direct[ci] = [0.0 for i in range(3)]
                    for k in range(0,3):
                        direct[ci][k] = jx*x_axis[k] + 0.5*jy*y_axis[k] + 0.5*jz*z_axis[k]
                    sum = direct[ci][0]*direct[ci][0] + direct[ci][1]*direct[ci][1] + direct[ci][2]*direct[ci][2]
                    sum = math.sqrt(sum)
                    for k in range(0,3):
                        direct[ci][k] /= sum
#                    print 'direct: %d %f %f %f' % (ci, direct[ci][0], direct[ci][1], direct[ci][2])
                    ci += 1

        for jx in range(-1, 2, 2):
            for jy in range(-1, 2, 2):
                for jz in range(-1, 2, 2):
                    direct[ci] = [0.0 for i in range(3)]
                    for k in range(0,3):
                        direct[ci][k] = 0.5*jx*x_axis[k] + jy*y_axis[k] + 0.5*jz*z_axis[k]
                    sum = direct[ci][0]*direct[ci][0] + direct[ci][1]*direct[ci][1] + direct[ci][2]*direct[ci][2]
                    sum = math.sqrt(sum)
                    for k in range(0,3):
                        direct[ci][k] /= sum
#                    print 'direct: %d %f %f %f' % (ci, direct[ci][0], direct[ci][1], direct[ci][2])
                    ci += 1

        for jx in range(-1, 2, 2):
            for jy in range(-1, 2, 2):
                for jz in range(-1, 2, 2):
                    direct[ci] = [0.0 for i in range(3)]
                    for k in range(0,3):
                        direct[ci][k] = 0.5*jx*x_axis[k] + 0.5*jy*y_axis[k] + jz*z_axis[k]
                    sum = direct[ci][0]*direct[ci][0] + direct[ci][1]*direct[ci][1] + direct[ci][2]*direct[ci][2]
                    sum = math.sqrt(sum)
                    for k in range(0,3):
                        direct[ci][k] /= sum
#                    print 'direct: %d %f %f %f' % (ci, direct[ci][0], direct[ci][1], direct[ci][2])
                    ci += 1

        
        # Determine dimension of pocket in each direction
        # origin (line_z) of line
        stored.pos = []
        cmd.select('s1','%s`%d'%a)
        cmd.iterate_state(1, 's1', 'stored.pos.append((x,y,z))')
        cmd.delete('s1')

        line_z = stored.pos[0];
        z2 = line_z[0]*line_z[0] + line_z[1]*line_z[1] + line_z[2]*line_z[2]
        
        numcavity = 0
        for m in range(0, 50):
            # directionality (line_n) of line
            line_n[0] = direct[m][0]
            line_n[1] = direct[m][1]
            line_n[2] = direct[m][2]
            n2 = line_n[0]*line_n[0] + line_n[1]*line_n[1] + line_n[2]*line_n[2]
               
            end_dir[0] = line_z[0] + line_n[0]
            end_dir[1] = line_z[1] + line_n[1]
            end_dir[2] = line_z[2] + line_n[2]
            
            maxalpha = 200.0
            cutvalue = 50
            
            # prefilter: check approximate directionality of CA of residue
            for p in cmd.index('Calpha'):
                stored.pos = []
                cmd.select('s1','%s`%d'%p)
                cmd.iterate_state(1, 's1', 'stored.pos.append((x,y,z))')
                cmd.delete('s1')
                com = stored.pos[0]
                
                if CosAngle(com, line_z, end_dir) &gt; 0.7 or Distance_Point_Point(com, line_z) &lt; 7.0:
                    cmd.select('s2','!element h and byres %s`%d'%p)
                    # all atoms of residue without hydrogens
                    for q in cmd.index('s2'):
                        stored.pos = []
                        atom_vdw = 0.0
                        cmd.select('s3','%s`%d'%q)
                        cmd.iterate_state(1, 's3', 'stored.pos.append((x,y,z))')
                        atom_vdw = cmd.iterate('s3', 'vdw')
                        cmd.delete('s3')
                        sphere_s = stored.pos[0]

                        s2 = sphere_s[0]*sphere_s[0] + sphere_s[1]*sphere_s[1] + sphere_s[2]*sphere_s[2];
                                
                        r_vdw = atom_vdw + 1.0;
                        R2 = r_vdw*r_vdw;
    #                            printf('uuu2: %f %f\n', s2, R2);
                                
                        a = n2;
                        b = 2*(line_n[0]*(line_z[0] - sphere_s[0]) + line_n[1]*(line_z[1] - sphere_s[1]) + line_n[2]*(line_z[2] - sphere_s[2]) );
                        c = z2 + s2 - 2*(line_z[0]*sphere_s[0] + line_z[1]*sphere_s[1] + line_z[2]*sphere_s[2]) - R2;
                                
                        # check if intersection with atom sphere
                        wurzel = b*b - 4*a*c;
                                
    #                            printf('wurzel: %f\n', wurzel);
                        if wurzel &gt; 0:
                            # take larger alpha value (a always &gt;0)
                            alpha1 = (-b - math.sqrt(wurzel))/(2*a);
                            alpha2 = (-b + math.sqrt(wurzel))/(2*a);
                            # only take solution in positive direction (otherwise opposite direct[])
    #                                printf('uuu3: %d %s : %d : %s %f : %f %f\n', p, conf[conf_no_if]-&gt;res[p].name, j, if_atom-&gt;name, r_vdw,  alpha1, alpha2);
                            if alpha1 &gt; 0:
                                if alpha1 &lt; maxalpha:
                                    maxalpha = alpha1;
    #                                       printf('uuu4: % 4d : % 6.2f % 6.2f --&gt; % 6.2f : % 6.2f % 6.2f % 6.2f % 6.2f : % 4s % 6.2f % 6.2f : % 6.2f % 6.2f % 6.2f : % 6.2f % 6.2f % 6.2f : % 6.2f % 6.2f % 6.2f : % 4d\n', j, alpha1, alpha2, maxalpha_conf[j], a, b, c, wurzel, if_atom-&gt;name, s2, R2, if_atom-&gt;x[0], if_atom-&gt;x[1], if_atom-&gt;x[2], line_z[0], line_z[1], line_z[2], end_dir[0], end_dir[1], end_dir[2], m);
                            elif alpha2 &gt; 0:
                                if alpha2 &lt; maxalpha:
                                    maxalpha = alpha2;
    #                                        printf('uuu5: % 4d : % 6.2f % 6.2f --&gt; % 6.2f : % 6.2f % 6.2f % 6.2f % 6.2f : % 4s % 6.2f % 6.2f : % 6.2f % 6.2f % 6.2f : % 6.2f % 6.2f % 6.2f : % 6.2f % 6.2f % 6.2f : % 4d\n', j, alpha1, alpha2, maxalpha_conf[j], a, b, c, wurzel, if_atom-&gt;name, s2, R2, if_atom-&gt;x[0], if_atom-&gt;x[1], if_atom-&gt;x[2], line_z[0], line_z[1], line_z[2], end_dir[0], end_dir[1], end_dir[2], m);
                
            # cavity
            if maxalpha &lt; cutvalue:
                numcavity += 1
                    
        return (numcavity/50)
#            tri_list[i]-&gt;ligand_size[0][m] = maxalpha;

#######################################################################################
def use_reduce(app):
	d_sel_pro = prepareProtein_dialog(app.root)
        print d_sel_pro.ok_flag
	if d_sel_pro.ok_flag == 0:
		return 0
                
        # find number of object in list
        object_list = []
        for na in cmd.get_names('objects'):
            try:
                object_list.append(na)
            except:
                pass

        # write pdb file
	for na in cmd.get_names('objects'):
            try:
                print na, d_sel_pro.object_name
                if na == d_sel_pro.object_name:
                    rem = na
                    cmd.select('pro', na)
                    cmd.save('prot_out.pdb','pro', 0, 'pdb')
                    cmd.delete('pro')
            except:
                pass
        
        # run reduce program
        os.system('cp %s/reduce .\n' % reduce_exe_dir)
        print 'cp %s/reduce .\n' % reduce_exe_dir
        comm1 = './reduce -build prot_out.pdb &gt; reduce_prep.pdb\n'
        print comm1
        os.system(comm1)
        
        # This is a check to see if the reduce_prep.pdb file is there.  (IDK why we need the nested try, but doesnt run without it)
        try: 
            Ri = open('reduce_prep.pdb', 'r')
            try:
                pass
            finally:
                Ri.close()    
        except IOError:
            print('\nError: can not find the file reduce_prep.pdb\n')
            sys.exit(0)
        
        # Open the reduce_prep.pdb file, obtain HIS protonation states, sort by res#, write out logfile
	Ri = open('reduce_prep.pdb', 'r')

        ci = 0
        cm = 0
        catoms = 0
        while Ri:
            line = Ri.readline()
            if line.find('USER  MOD S') &gt; -1:
                #print line
                if line[25:28] == 'HIS':
                    ci += 1
                    #
                    flip_state = line[34:38].strip()
                    if flip_state == 'FLIP':
                        cm += 1
                elif line[25:28] == 'ASN':
                    flip_state = line[34:38].strip()
                    if flip_state == 'FLIP':
                        cm += 1
                elif line[25:28] == 'GLN':
                    flip_state = line[34:38].strip()
                    if flip_state == 'FLIP':
                        cm += 1
                    '''
                    protonation =  line[38:45].strip()
                    print '%s,%s\n' % (line[25:28], protonation)
                    if protonation == 'no HD1':
                        rlog.write('%s\t%s\tHIE\n' % (line[25:28], line[20:24]))
                    elif protonation == 'no HE2':
                        rlog.write('%s\t%s\tHID\n' % (line[25:28], line[20:24]))
                    elif protonation == '+bothHN':
                        rlog.write('%s\t%s\tHIP\n' % (line[25:28], line[20:24]))
                    '''
            catoms += 1
            if line == '':
                break
        # Rewind, allocate the arrays to store res_num &amp; protonation &amp; order
        order = [0 for i in range(ci)]
        resnum = [0 for i in range(ci)]
        protna = [[] for i in range(ci)]
        order2 = [0 for i in range(cm)]
        resnum2 = [0 for i in range(cm)]
        flipped = [[] for i in range(cm)]

        Ri.seek(0)
        # Store data to the arrays
        j = 0
        m = 0
        while Ri:
            line = Ri.readline()
            #for i in range (ci):
            if line.find('USER  MOD S') &gt; -1:
                #print line
                if line[25:28] == 'HIS':
                    protonation =  line[38:45].strip()
                    resnum[j] = int(line[20:24].strip())
                    #print 'MLD: %s,%s\n' % (line[25:28], protonation)
                    if protonation == 'no HD1':
                        protna[j]= 'HIE'
                        j += 1
                        #
                        flip_state = line[34:38].strip()
                        if flip_state == 'FLIP':
                            flipped[m] = 'HIE'
                            resnum2[m] = int(line[20:24].strip())
                            m += 1
                    elif protonation == 'no HE2':
                        protna[j]= 'HID'
                        j += 1 
                        #
                        flip_state = line[34:38].strip()
                        if flip_state == 'FLIP':
                            flipped[m] = 'HID'
                            resnum2[m] = int(line[20:24].strip())
                            m += 1
                    elif protonation == '+bothHN':
                        protna[j]= 'HIP' 
                        j += 1
                        #
                        flip_state = line[34:38].strip()
                        if flip_state == 'FLIP':
                            flipped[m] = 'HIP'
                            resnum2[m] = int(line[20:24].strip())
                            m += 1
                elif line[25:28] == 'ASN':
                    flip_state = line[34:38].strip()
                    if flip_state == 'FLIP':
                        flipped[m] = 'ASN'
                        resnum2[m] = int(line[20:24].strip())
                        m += 1
                elif line[25:28] == 'GLN':
                    flip_state = line[34:38].strip()
                    if flip_state == 'FLIP':
                        flipped[m] = 'GLN'
                        resnum2[m] = int(line[20:24].strip())
                        m += 1
            if line == '':
                break

        
        # Sort the array
        for i in range(ci):
            order[i] = i

        for i1 in range(ci):
            for i2 in range(i1+1, ci):
                if resnum[order[i2]] &lt; resnum[order[i1]]:
                    tmpo = order[i1]
                    order[i1] = order[i2]
                    order[i2] = tmpo

        # Sort the array
        for i in range(cm):
            order2[i] = i

        for i1 in range(cm):
            for i2 in range(i1+1, cm):
                if resnum2[order2[i2]] &lt; resnum2[order2[i1]]:
                    tmpo = order2[i1]
                    order2[i1] = order2[i2]
                    order2[i2] = tmpo

        # Open the log file and write 
        fo = open('Reduce.log', 'w')
        fo.write('Histidine states: \n')
        for i1 in range(ci):
            fo.write('%s %d\n' % (protna[order[i1]], resnum[order[i1]]))
            #fo.write('%-10s % 12.3f % 12.3f % 12.3f\n' % (score_name[order[i1]], total_score[order[i1]], score_val[order[i1]], lig_score[order[i1]]))
        fo.write('\nHis, Asn or Gln sidechains flipped: \n')
        for i1 in range(cm):
            fo.write('%s %d\n' % (flipped[order2[i1]], resnum2[order2[i1]]))
        fo.close()
                       
        # Write out Latest .pdb to be used in loop_ligand_scoreing
        Ri.seek(0)
        # Regular Expression (creates a pattern for the hydrogens)
        p = re.compile('H[A-Z]+')
        file_pdb = 'Fin_reduce.pdb'
        fpdb = open(file_pdb, 'w')

        cur_num = 0
        prev_num = -1
        m = -1
        for line in Ri:
            # If the line does not have a hydrogen
	    if (line[0:4] == 'ATOM' or line[0:6] == 'HETATM') and p.match(line[12:16]) == None and p.match(line[13:16]) == None and line[13] != 'H' and (line[13] != ' ' or (line[14:16] != 'H1' and line[14:16] != 'H2')):
	    	if line[17:20] == 'HIS':
	            cur_num =  int(line[22:26])
                    if cur_num in resnum:
                        #print prev_num, cur_num
                        # Need a way to track residues.  Want to change the resdiue HIS to HIE not just a single line
                        if prev_num != cur_num:
                            m += 1
                            prev_num = cur_num
                            print line, protna[order[m]]
                            line_1 = line[0:17] + protna[order[m]] + ' ' + line[21:]
                            #print line_1
                        else:
                            line_1 = line[0:17] + protna[order[m]] + ' ' + line[21:]
                    else :
                            line_1 = line
            	else :
                	line_1 = line
                fpdb.write(line_1)

        Ri.close()
        fpdb.close()
        
        # read new pdb file
        cmd.load('Fin_reduce.pdb', rem)
        print rem
	cmd.split_states(rem)
 	cmd.delete(name=rem)
	cmd.delete('%s_0001' % (rem))
        tmp_obj = rem + '_0002'
   
        # change object name
	for na in cmd.get_names('objects'):
            try:
                if na == tmp_obj:
                    cmd.set_name(na, rem)   
            except:
                pass

        # resort list of objects
	my_view= cmd.get_view()

        for obj in object_list:
            for na in cmd.get_names('objects'):
                try:
                    if na == obj:
                        cmd.copy('tmp_obj', na)
                        cmd.delete(na)
                        cmd.set_name('tmp_obj', na)  
                except:
                    pass
                
	cmd.set_view(my_view)

#        rootframe.destroy()


	os.remove('prot_out.pdb')
        
        red_mes = reduceMessage(app.root)
	os.remove('reduce')
	os.remove('Reduce.log')
	os.remove('reduce_prep.pdb')


#######################################################################################
def remove_waters(app):
	d_sel_wat = prepareProtein_dialog(app.root)
	if d_sel_wat.ok_flag == 0:
		return 0

        d_spec_wat = specifyWater_dialog(app.root)
	if d_spec_wat.ok_flag == 0:
		return 0

	for na in cmd.get_names('objects'):
#            try:
                if na == d_sel_wat.object_name:
                    cmd.select('pro', na)
                    numwat = cmd.select('pro2', 'pro and resn HOH+WAT+SOL and symbol o')
#                    print numwat
#                    water_list = []
                    cmd.select('waters', 'resn HOH and !resn HOH')
                    for a in cmd.index('pro2'):
#                        print a
                        cutoff=3.6
                        angle=70.0
                        hb2 = cmd.find_pairs(a,'((byres pro) and symbol n+o and !resn HOH+WAT+SOL)',mode=1,cutoff=cutoff,angle=angle)
                        num_hbonds_to_protein = len(hb2)
                        hb3 = cmd.find_pairs(a,'((byres pro) &amp; resn HOH+WAT+SOL and  symbol o)',mode=0,cutoff=cutoff)
                        num_hbonds_to_water = len(hb3)
                        num_hbonds_total = num_hbonds_to_protein + num_hbonds_to_water
                        
#                        prop_cavity = calculateSolventExposure(a, na)
#                        print prop_cavity
                        
#                        print '%d %d %d' % (num_hbonds_to_protein, num_hbonds_to_water, num_hbonds_total)
                        if num_hbonds_to_protein &lt; d_spec_wat.num_hbonds_to_protein or num_hbonds_to_water &lt; d_spec_wat.num_hbonds_to_water or num_hbonds_total &lt; d_spec_wat.num_hbonds_total:
                            cmd.select('waters', 'byres(?waters) or byres(%s`%d)'%a)
#                            cmd.remove(a)
                            
#                            water_list.append(a)
#                    print water_list
#                    cmd.select('waters', water_list)
#                    cmd.select('waters','%s`%d'%water_list)
                    cmd.enable('waters')

                            
                    

                    cmd.delete('pro')
                    cmd.delete('pro2')
#            except:
#                pass
    
#######################################################################################
def add_hydrogens(app):
	d_add_hyd = prepareProtein_dialog(app.root)
	if d_add_hyd.ok_flag == 0:
		return 0
                
#        d_add_hyd.cancel()

#        rootframe = Tk()
#        info = InfoMessage(master=rootframe, text='Please be patient,\nwhile disulfide bridges will be identified, hydrogens added, atomtypes and charges associated.')
        # find number of object in list
        object_list = []
        for na in cmd.get_names('objects'):
            try:
                object_list.append(na)
            except:
                pass
        
	# write out protein pdb in AMBER-compatible mode
	stored.chain = []
	stored.resnam = []
	stored.resid = []
        cof_flag = []
	for na in cmd.get_names('objects'):
            try:
                if na == d_add_hyd.object_name:
                    cmd.select('pro', na)
                    cmd.select('pro2', 'pro and resn %s' % PDBcode_protein)
                    # check for co-factors
                    cf = 0
                    for pco, fco in zip(PDBcode_cofactors, filename_cofactors):
                        cmd.select('pro3', 'pro and resn %s' % pco)
                        if cmd.count_atoms('pro3') &gt; 0:
                            cof_flag.append(cf)
                        cf += 1
                        cmd.delete('pro3')
                    cmd.select('pro4', 'pro and not resn %s' % PDBcode_protein_water)
                    L = cmd.count_atoms('pro4')
                    if L &gt; 0:
                        stored.list = []
                        cmd.iterate('pro4', 'stored.list.append((resi, resn))')
                        # remove duplicates
                        du = {}
                        for uu in stored.list:
                            du[uu] = uu
                        fin_list = du.values()
                        fin_list.sort()
                        strg1 = ''
                        for sa, sb in fin_list:
                            strg1 += '%s %s  ' % (sa, sb)
                        strg2 = 'The following residues are unknown by the force field: %s \n\n Please separate ligand into different object and/or define co-factors in folder %s' % (strg1, library_dir)    
                        
                        tkMessageBox.showwarning('Unknown residues', strg2)
                        cmd.delete('pro')
                        cmd.delete('pro2')
                        cmd.delete('pro4')
                        return 0
                    cmd.delete('pro4')
                    
                    
                    L = cmd.count_atoms('pro2')
                    if L &gt; 0:
                            rem = na
                            find_disulfide_bridges('pro2') 
                            cmd.save('prot_out.pdb','pro', 0, 'pdb')
                            cmd.select('sele2', 'pro and name CA+FE')
                            cmd.iterate ('sele2', 'stored.chain.append(chain)')
                            cmd.iterate ('sele2', 'stored.resnam.append(resn)')
                            cmd.iterate ('sele2', 'stored.resid.append(resi)')
                            find_disulfide_bridges_2('prot_out.pdb', cof_flag, '000')
                            # read first residue number in prot_out.pdb file for proper disulfide numbering
                            for line in open('prot_out.pdb'):
                                if line.find('ATOM') &gt;= 0:
                                    resid_zero = int(line[22:26].strip())
                                    break
                                                        
                            ResortPDB4Amber('prot_out.pdb') 
                    else:
                        return 0
                    cmd.delete('pro')
                    cmd.delete('pro2')

            except:
                pass
        # read first residue number in prot_out.pdb file for proper disulfide numbering
        for line in open('prot_out.pdb'):
            if line.find('ATOM') &gt;= 0:
                resid_zero = int(line[22:26].strip())
                break
        
        # write leapP.in file
        fout = open('leapP.in','w')
        fout.write('source leaprc.gaff\n')
        fout.write('source leaprc.ff03\n')
        for j in cof_flag:
            fout.write('loadoff %s.lib\n' % (filename_cofactors[j]))
            fout.write('fcof = loadamberparams %s.frcmod\n' % (filename_cofactors[j]))
        fout.write('prot = loadpdb prot_out.pdb\n')
        # add disulfide bridges
        for ds1_i, ds1_n, ds1_a, ds2_i, ds2_n, ds2_a in zip(disulfide_A, disulfide_A_name, disulfide_A_atom, disulfide_B, disulfide_B_name, disulfide_B_atom):
            fout.write('bond prot.%d.%s prot.%d.%s\n' % (int(ds1_i)+resid_zero-1, ds1_a, int(ds2_i)+resid_zero-1, ds2_a))
        fout.write('saveoff prot prot.lib\n')
        fout.write('saveamberparm prot prot.top prot.trj\n')
	fout.write('savepdb prot prot_amber.pdb\n')
	fout.write('quit\n')
	fout.close()

	os.system('mkdir tmp_amber')
	os.system('cp prot_out.pdb leapP.in ./tmp_amber/')
        for j in cof_flag:
            os.system('cp %s/%s.lib %s/%s.frcmod ./tmp_amber/' % (library_dir, filename_cofactors[j], library_dir, filename_cofactors[j]))
	os.system('cd ./tmp_amber; %s/exe/tleap -f leapP.in' % (amber_dir))
	os.system('cp ./tmp_amber/prot_amber.pdb .')
#	os.system('rm -rf tmp_amber')

	cmd.load('prot_amber.pdb', rem)
	cmd.split_states(rem)
 	cmd.delete(name=rem)
	cmd.delete('%s_0001' % (rem))
        tmp_obj = rem + '_0002'
   
	# reset residue numbers
	stored.chain2 = []
	stored.resnam2 = []
	stored.resid2 = []
	for na in cmd.get_names('objects'):
            try:
                if na == tmp_obj:
                    cmd.select('pro', na)
                    cmd.select('pro2', 'pro and resn %s' % PDBcode_protein)
                    L = cmd.count_atoms('pro2')
                    if L &gt; 0:
                        cmd.iterate ('pro2', 'stored.chain2.append(chain)')
                        cmd.iterate ('pro2', 'stored.resnam2.append(resn)')
                        cmd.iterate ('pro2', 'stored.resid2.append(resi)')
                        ci = 0
                        k = 0 
                        oldresid = int(stored.resid2[0]) 
                        for i in stored.resid2:
                            j = int(i) 
                            if j &gt; oldresid:
                                ci = ci + 1
                                oldresid = j
                            stored.resid2[k] = stored.resid[ci]
                            stored.chain2[k] = stored.chain[ci]
                            k = k + 1 
                        cmd.alter('pro2','resi=str(stored.resid2.pop(0))')
                        cmd.alter('pro2','chain=str(stored.chain2.pop(0))')
                        cmd.disable(na)
                        cmd.enable(na) 
                        cmd.set_name(na, rem)   
             
                    
                    cmd.delete('pro')
                    cmd.delete('pro2')
            except:
                pass

        # resort list of objects
	my_view = cmd.get_view()

        for obj in object_list:
            for na in cmd.get_names('objects'):
                try:
                    if na == obj:
                        cmd.copy('tmp_obj', na)
                        cmd.delete(na)
                        cmd.set_name('tmp_obj', na)  
                except:
                    pass
                
	cmd.set_view(my_view)

#        rootframe.destroy()


	os.remove('prot_out.pdb')
	os.remove('prot_amber.pdb')
	os.remove('leapP.in')

#######################################################################################
def write_mol2_select(app):
    d_sel_obj = selectObject_dialog(app.root)

    if d_sel_obj.ok_flag == 0:
        return 0

    for na in cmd.get_names('objects'):
        try:
            if na == d_sel_obj.object_name:
                write_mol2(na, '%s' % (na))
        except:
            return 0
                

#######################################################################################
def modify_his_state(app, usersel):
        try:
            cmd.select('sele_t', usersel)
        except:
            tkMessageBox.showwarning('Could not find any selected atoms','Please select object first.')
            return 0
        cmd.select('sele2', 'sele_t and resn HIS+HIE+HID+HIP')
	stored.resnam = []
	cmd.iterate ('sele2', 'stored.resnam.append(resn)')
        L = cmd.count_atoms('sele2')
	if L == 0:
		tkMessageBox.showwarning('Could not find any selected atoms','Please select object first.')
		return 0
        d_his = his_dialog(app.root)
        if d_his.ok_flag == 0:
            return 0
        hisnam = str(d_his.v0.get())
#        print hisnam
#        cmd.alter(na, 'resn=\'%s\'' % (aaa))
	stored.resnam_new = []
        for i in stored.resnam:
            stored.resnam_new.append(hisnam)
#        print stored.resnam
#        print stored.resnam_new
        cmd.alter('sele2','resn=stored.resnam_new.pop(0)')
        
        cmd.delete('sele2')
        cmd.delete('sele_t')
        
#######################################################################################
def color_by_bfactor(app):
    d_col_b = prepareProtein_dialog(app.root)
    if d_col_b.ok_flag == 0:
            return 0
                
    for na in cmd.get_names('objects'):
        try:
            if na == d_col_b.object_name:
                cmd.select('pro', na)
                selection = 'pro'
        except:
            return 0
    


    min_b = 5.
    max_b = 60.
    nbins = 50
    item = 'b'
    sat = 1.0
    value = 1.0
    # get list of B-factors from selection
    m = cmd.get_model(selection)
    sel = []
    b_list = []

    for i in range(len(m.atom)):
        b_list.append(m.atom[i].b)
    
    bin_width = (max_b - min_b)/nbins
    sel.append(selection + ' and (%s &lt; %4.4g' % (item,min_b + bin_width) + ' or %s = %4.4g' % (item,min_b + bin_width) + ')')
    for j in range(1,nbins):
        sel.append(selection + ' and %s &gt; %4.4g' % (item,min_b + j*bin_width))

    # call the function to create the gradient which returns a list of colours
#    colours = make_gradient(sel,gradient,nbins,sat,value, user_rgb)

    gradient = 'bgr'
    col=[]
    colours=[]
    for j in range(nbins):
      # must append the str(sel[j]) to the color name so that it is unique 
      # for the selection
      colours.append('col' + gradient + str(j) + str(sel[j]))
      # coldesc.append('col' + str(sel[j]) + str(j))

      # create colors using hsv scale (fractional) starting at blue(.6666667) 
      # through red(0.00000) in intervals of .6666667/(nbins -1) (the 'nbins-1' 
      # ensures that the last color is, in fact, red (0)
      # rewrote this to use the colorsys module to convert hsv to rgb
      hsv = (colorsys.TWO_THIRD - colorsys.TWO_THIRD * float(j) / (nbins-1), sat, value)
      #convert to rgb and append to color list
      rgb = colorsys.hsv_to_rgb(hsv[0],hsv[1],hsv[2])

      col.append(rgb)
      #cmd.set_color('col' + gradient + str(j),col[j])
      #print col[j],'defined as ', 'col'+str(j)+str(sel[j])
      cmd.set_color('col' + gradient + str(j) + str(sel[j]),col[j])
      #print col[j],'defined as ', 'col'+str(j)

    # do the colouring now
    for j in range(nbins):
        cmd.color(colours[j], sel[j])
        
    cmd.delete('pro')

#######################################################################################
def compute_bfactor(app):
    pass

#######################################################################################
def convert_gro_pdb(app):
    # read ffamber_vs_amber.txt file and store information
    path1 = os.environ.get('PYMOL_PATH')
    filename = '%s\modules\pmg_tk\startup\ffamber_vs_amber.txt' % (path1)
    try:
        fi = open(filename, 'r')
    except:
        print 'Cannot open file %s.' % (filename)
        return 0
        
    for i in fi:
        if len(i) &gt; 5:
            line = i.strip()
            

#######################################################################################
def readAmberLibrary(app):
	global PDBcode_cofactors, filename_cofactors, PDBcode_aminoacids, PDBcode_protein, PDBcode_protein_water
	global bond_info_res1, bond_info_atm1, bond_info_res2, bond_info_atm2, bond_info_dist
    
	# read co-factor information
	filename = library_dir + '/cofactors.txt'
	try:
		fi = open(filename, 'r')
	except:
		tkMessageBox.showwarning(
			"Missing file cofactors.txt",
			"Please, specify correct location of library_dir (e.g. /usr/local/AMBER_library) in Settings_Linux.txt file"
		)
		modify_settings(app)
		
	fi.readline()
	PDBcode_cofactors = []
	filename_cofactors = []
	while 1:
		line = fi.readline()
		if len(line) &gt; 5:
			dt = line.split()
			PDBcode_cofactors.append(dt[0])
			filename_cofactors.append(dt[1])
		else:
			break
    
	PDBcode_aminoacids = 'ALA+ARG+ASH+ASN+ASP+CYS+CYX+CY1+GLH+GLN+GLU+GLY+HIS+HIE+HID+HIP+ILE+LEU+LYS+MET+PHE+PRO+SER+THR+TRP+TYR+VAL'    
	PDBcode_protein = 'ALA+ARG+ASH+ASN+ASP+CYS+CYX+CY1+GLH+GLN+GLU+GLY+HIS+HIE+HID+HIP+ILE+LEU+LYS+MET+PHE+PRO+SER+THR+TRP+TYR+VAL'
	for i in PDBcode_cofactors:
		PDBcode_protein += '+%s' % i
        
	PDBcode_protein_water = PDBcode_protein + '+HOH+WAT'
    
	# read non-peptide bond information
	filename = library_dir + '/bonding.txt'
	fi = open(filename, 'r')
	fi.readline()
	bond_info_res1 = []
	bond_info_atm1 = []
	bond_info_res2 = []
	bond_info_atm2 = []
	bond_info_dist = []
	while 1:
		line = fi.readline()
		if len(line) &gt; 5:
			dt = line.split()
			bond_info_res1.append(dt[0])
			bond_info_atm1.append(dt[1])
			bond_info_res2.append(dt[2])
			bond_info_atm2.append(dt[3])
			bond_info_dist.append(dt[4])
		else:
			break
    
#    print PDBcode_protein

#######################################################################################
class modifySettingsFile:
	def __init__(self, top):
		self.dialog = Pmw.Dialog(top,
								buttons = ('Exit','Save to file','Reset to defaults'),
								defaultbutton = 'Exit',
								title = 'Generate/Modify Settings_Linux.txt file',
								command = self.apply)

		self.curdir = os.getcwd()
 	                                
		master = self.dialog.interior()

		Tkinter.Label(master, text='Generate new and modify existing Settings_Linux.txt file').pack(expand = 1, fill = 'both', padx = 5, pady = 5)

		nb1 = Pmw.NoteBook(master)

		# username page
		user_page = nb1.add('Username')

		Tkinter.Label(user_page, text='username:').grid(row=0, column=0, sticky=W, padx = 5, pady=1)
		self.e_username = Tkinter.Entry(user_page, width=70)
		self.e_username.insert(0, username)
		self.e_username.grid(row=0, column=1, sticky=W, padx = 5, pady=1)


		# MM page
		MM_page = nb1.add('Amber')

		Tkinter.Label(MM_page, text='library_dir (library containing cofactors for Amber):').grid(row=0, column=0, sticky=W, padx = 5, pady=1)
		self.e_library_dir = Tkinter.Entry(MM_page, width=70)
		self.e_library_dir.insert(0, library_dir)
		self.e_library_dir.grid(row=0, column=1, sticky=W, padx = 5, pady=1)
		b_library_dir = Tkinter.Button(MM_page, text='Browse', command = lambda: self.searchFOLDER(library_dir,self.e_library_dir)).grid(row=0, column=2, sticky=W, padx = 5, pady=1)

		Tkinter.Label(MM_page, text='amber_dir (main amber directory = $AMBERHOME):').grid(row=1, column=0, sticky=W, padx = 5, pady=1)
		self.e_amber_dir = Tkinter.Entry(MM_page, width=70)
		self.e_amber_dir.insert(0, amber_dir)
		self.e_amber_dir.grid(row=1, column=1, sticky=W, padx = 5, pady=1)
		b_amber_dir = Tkinter.Button(MM_page, text='Browse', command = lambda: self.searchFOLDER(amber_dir,self.e_amber_dir)).grid(row=1, column=2, sticky=W, padx = 5, pady=1)

		Tkinter.Label(MM_page, text='sie_dir (directory containing SIE executable):').grid(row=2, column=0, sticky=W, padx = 5, pady=1)
		self.e_sie_dir = Tkinter.Entry(MM_page, width=70)
		self.e_sie_dir.insert(0, sie_dir)
		self.e_sie_dir.grid(row=2, column=1, sticky=W, padx = 5, pady=1)
		b_sie_dir = Tkinter.Button(MM_page, text='Browse', command = lambda: self.searchFOLDER(sie_dir,self.e_sie_dir)).grid(row=2, column=2, sticky=W, padx = 5, pady=1)
		
		Tkinter.Label(MM_page, text='changepdb_dir (directory containing changepdb executable):').grid(row=3, column=0, sticky=W, padx = 5, pady=1)
		self.e_changepdb_dir = Tkinter.Entry(MM_page, width=70)
		self.e_changepdb_dir.insert(0, changepdb_dir)
		self.e_changepdb_dir.grid(row=3, column=1, sticky=W, padx = 5, pady=1)
		b_changepdb_dir = Tkinter.Button(MM_page, text='Browse', command = lambda: self.searchFOLDER(changepdb_dir,self.e_changepdb_dir)).grid(row=3, column=2, sticky=W, padx = 5, pady=1)

		Tkinter.Label(MM_page, text='changecrd_dir (directory containing changecrd executable):').grid(row=4, column=0, sticky=W, padx = 5, pady=1)
		self.e_changecrd_dir = Tkinter.Entry(MM_page, width=70)
		self.e_changecrd_dir.insert(0, changecrd_dir)
		self.e_changecrd_dir.grid(row=4, column=1, sticky=W, padx = 5, pady=1)
		b_changecrd_dir = Tkinter.Button(MM_page, text='Browse', command = lambda: self.searchFOLDER(changecrd_dir,self.e_changecrd_dir)).grid(row=4, column=2, sticky=W, padx = 5, pady=1)
		
		Tkinter.Label(MM_page, text='reduce_exe_dir (directory containing reduce executable):').grid(row=5, column=0, sticky=W, padx = 5, pady=1)
		self.e_reduce_exe_dir = Tkinter.Entry(MM_page, width=70)
		self.e_reduce_exe_dir.insert(0, reduce_exe_dir)
		self.e_reduce_exe_dir.grid(row=5, column=1, sticky=W, padx = 5, pady=1)
		b_reduce_exe_dir = Tkinter.Button(MM_page, text='Browse', command = lambda: self.searchFOLDER(reduce_exe_dir,self.e_reduce_exe_dir)).grid(row=5, column=2, sticky=W, padx = 5, pady=1)


		# Vina page
		Vina_page = nb1.add('AutoDock Vina')

		Tkinter.Label(Vina_page, text='autodock_dir (library for ligand datasets):').grid(row=0, column=0, sticky=W, padx = 5, pady=1)
		self.e_autodock_dir = Tkinter.Entry(Vina_page, width=70)
		self.e_autodock_dir.insert(0, autodock_dir)
		self.e_autodock_dir.grid(row=0, column=1, sticky=W, padx = 5, pady=1)
		b_autodock_dir = Tkinter.Button(Vina_page, text='Browse', command = lambda: self.searchFOLDER(autodock_dir,self.e_autodock_dir)).grid(row=0, column=2, sticky=W, padx = 5, pady=1)

		Tkinter.Label(Vina_page, text='autodock_exe_dir (directory containing AutoDock Tools):').grid(row=1, column=0, sticky=W, padx = 5, pady=1)
		self.e_autodock_exe_dir = Tkinter.Entry(Vina_page, width=70)
		self.e_autodock_exe_dir.insert(0, autodock_exe_dir)
		self.e_autodock_exe_dir.grid(row=1, column=1, sticky=W, padx = 5, pady=1)
		b_autodock_exe_dir = Tkinter.Button(Vina_page, text='Browse', command = lambda: self.searchFOLDER(autodock_exe_dir,self.e_autodock_exe_dir)).grid(row=1, column=2, sticky=W, padx = 5, pady=1)

		Tkinter.Label(Vina_page, text='vina_dir (directory containing AutoDock Vina executable):').grid(row=2, column=0, sticky=W, padx = 5, pady=1)
		self.e_vina_dir = Tkinter.Entry(Vina_page, width=70)
		self.e_vina_dir.insert(0, vina_dir)
		self.e_vina_dir.grid(row=2, column=1, sticky=W, padx = 5, pady=1)
		b_vina_dir = Tkinter.Button(Vina_page, text='Browse', command = lambda: self.searchFOLDER(vina_dir,self.e_vina_dir)).grid(row=2, column=2, sticky=W, padx = 5, pady=1)


		# Slide page
		Slide_page = nb1.add('Slide docking')

		Tkinter.Label(Slide_page, text='slide_dir (library for ligand datasets):').grid(row=0, column=0, sticky=W, padx = 5, pady=1)
		self.e_slide_dir = Tkinter.Entry(Slide_page, width=70)
		self.e_slide_dir.insert(0, slide_dir)
		self.e_slide_dir.grid(row=0, column=1, sticky=W, padx = 5, pady=1)
		b_slide_dir = Tkinter.Button(Slide_page, text='Browse', command = lambda: self.searchFOLDER(slide_dir,self.e_slide_dir)).grid(row=0, column=2, sticky=W, padx = 5, pady=1)

		Tkinter.Label(Slide_page, text='slide_main_dir (base directory for Slide):').grid(row=1, column=0, sticky=W, padx = 5, pady=1)
		self.e_slide_main_dir = Tkinter.Entry(Slide_page, width=70)
		self.e_slide_main_dir.insert(0, slide_main_dir)
		self.e_slide_main_dir.grid(row=1, column=1, sticky=W, padx = 5, pady=1)
		b_slide_main_dir = Tkinter.Button(Slide_page, text='Browse', command = lambda: self.searchFOLDER(slide_main_dir,self.e_slide_main_dir)).grid(row=1, column=2, sticky=W, padx = 5, pady=1)

		Tkinter.Label(Slide_page, text='slide_exe_dir (directory containing Slide executable):').grid(row=2, column=0, sticky=W, padx = 5, pady=1)
		self.e_slide_exe_dir = Tkinter.Entry(Slide_page, width=70)
		self.e_slide_exe_dir.insert(0, slide_exe_dir)
		self.e_slide_exe_dir.grid(row=2, column=1, sticky=W, padx = 5, pady=1)
		b_slide_exe_dir = Tkinter.Button(Slide_page, text='Browse', command = lambda: self.searchFOLDER(slide_exe_dir,self.e_slide_exe_dir)).grid(row=2, column=2, sticky=W, padx = 5, pady=1)

		Tkinter.Label(Slide_page, text='slide_main_dir_multiple (base directory for Slide (multiple poses)):').grid(row=3, column=0, sticky=W, padx = 5, pady=1)
		self.e_slide_main_dir_multiple = Tkinter.Entry(Slide_page, width=70)
		self.e_slide_main_dir_multiple.insert(0, slide_main_dir_multiple)
		self.e_slide_main_dir_multiple.grid(row=3, column=1, sticky=W, padx = 5, pady=1)
		b_slide_main_dir_multiple = Tkinter.Button(Slide_page, text='Browse', command = lambda: self.searchFOLDER(slide_main_dir_multiple,self.e_slide_main_dir_multiple)).grid(row=3, column=2, sticky=W, padx = 5, pady=1)

		Tkinter.Label(Slide_page, text='slide_exe_dir_multiple (directory containing Slide executable (multiple poses)):').grid(row=4, column=0, sticky=W, padx = 5, pady=1)
		self.e_slide_exe_dir_multiple = Tkinter.Entry(Slide_page, width=70)
		self.e_slide_exe_dir_multiple.insert(0, slide_exe_dir_multiple)
		self.e_slide_exe_dir_multiple.grid(row=4, column=1, sticky=W, padx = 5, pady=1)
		b_slide_exe_dir_multiple = Tkinter.Button(Slide_page, text='Browse', command = lambda: self.searchFOLDER(slide_exe_dir_multiple,self.e_slide_exe_dir_multiple)).grid(row=4, column=2, sticky=W, padx = 5, pady=1)

		Tkinter.Label(Slide_page, text='slide_data_dir (directory for storing data):').grid(row=5, column=0, sticky=W, padx = 5, pady=1)
		self.e_slide_data_dir = Tkinter.Entry(Slide_page, width=70)
		self.e_slide_data_dir.insert(0, slide_data_dir)
		self.e_slide_data_dir.grid(row=5, column=1, sticky=W, padx = 5, pady=1)
		b_slide_data_dir = Tkinter.Button(Slide_page, text='Browse', command = lambda: self.searchFOLDER(slide_data_dir,self.e_slide_data_dir)).grid(row=5, column=2, sticky=W, padx = 5, pady=1)

		Tkinter.Label(Slide_page, text='slide_sort (directory containing sort program for Slide output):').grid(row=6, column=0, sticky=W, padx = 5, pady=1)
		self.e_slide_sort = Tkinter.Entry(Slide_page, width=70)
		self.e_slide_sort.insert(0, slide_sort)
		self.e_slide_sort.grid(row=6, column=1, sticky=W, padx = 5, pady=1)
		b_slide_sort = Tkinter.Button(Slide_page, text='Browse', command = lambda: self.searchFOLDER(slide_sort,self.e_slide_sort)).grid(row=6, column=2, sticky=W, padx = 5, pady=1)


		# QSAR page
		QSAR_page = nb1.add('Symposar/Raptor')

		Tkinter.Label(QSAR_page, text='symposar_exe_dir (library for ligand datasets):').grid(row=0, column=0, sticky=W, padx = 5, pady=1)
		self.e_symposar_exe_dir = Tkinter.Entry(QSAR_page, width=70)
		self.e_symposar_exe_dir.insert(0, symposar_exe_dir)
		self.e_symposar_exe_dir.grid(row=0, column=1, sticky=W, padx = 5, pady=1)
		b_symposar_exe_dir = Tkinter.Button(QSAR_page, text='Browse', command = lambda: self.searchFOLDER(symposar_exe_dir,self.e_symposar_exe_dir)).grid(row=0, column=2, sticky=W, padx = 5, pady=1)

		Tkinter.Label(QSAR_page, text='raptor_exe_dir (library for ligand datasets):').grid(row=1, column=0, sticky=W, padx = 5, pady=1)
		self.e_raptor_exe_dir = Tkinter.Entry(QSAR_page, width=70)
		self.e_raptor_exe_dir.insert(0, raptor_exe_dir)
		self.e_raptor_exe_dir.grid(row=1, column=1, sticky=W, padx = 5, pady=1)
		b_raptor_exe_dir = Tkinter.Button(QSAR_page, text='Browse', command = lambda: self.searchFOLDER(raptor_exe_dir,self.e_raptor_exe_dir)).grid(row=1, column=2, sticky=W, padx = 5, pady=1)


		# Infrastructure page
		Cluster_page = nb1.add('Cluster infrastructure')
	
		Tkinter.Label(Cluster_page, text='Cluster #:').grid(row=0, column=0, sticky=W, padx = 5, pady=1)
		Tkinter.Label(Cluster_page, text='Cluster name/address:').grid(row=0, column=1, sticky=W, padx = 5, pady=1)
		Tkinter.Label(Cluster_page, text='max. # \nof \nprocessors:').grid(row=0, column=2, sticky=W, padx = 5, pady=1)
		Tkinter.Label(Cluster_page, text='SSH \nport:').grid(row=0, column=3, sticky=W, padx = 5, pady=1)
		Tkinter.Label(Cluster_page, text='Queue:').grid(row=0, column=4, sticky=W, padx = 5, pady=1)
		Tkinter.Label(Cluster_page, text='Home directory on cluster:').grid(row=0, column=5, sticky=W, padx = 5, pady=1)
		Tkinter.Label(Cluster_page, text='$AMBERHOME on cluster:').grid(row=0, column=6, sticky=W, padx = 5, pady=1)


		self.cb_aa = [[] for i in range(10)]
		self.e_SERVER_nodename = ["" for i in range(10)]
		self.e_SERVER_max_proc = ["0" for i in range(10)]
		self.e_SERVER_ssh_port = ["" for i in range(10)]
		self.e_SERVER_home_dir = ["" for i in range(10)]
		self.e_SERVER_amber_dir = ["" for i in range(10)]
		self.e_SERVER_queue_name = ["" for i in range(10)]
		self.v_aa = []
		cj = 0
		for i in range(10):
			if cj &lt; SERVER_number_of:
				var = IntVar()
				self.cb_aa[cj] = Checkbutton(Cluster_page, text=str(i+1), variable=var)
				self.cb_aa[cj].grid(row=cj+1, column=0, sticky=W, padx=5)
				self.v_aa.append(var)
				self.cb_aa[cj].select()

				self.e_SERVER_nodename[cj] = Tkinter.Entry(Cluster_page, width=25)
				self.e_SERVER_nodename[cj].insert(0, SERVER_nodename[cj])
				self.e_SERVER_nodename[cj].grid(row=cj+1, column=1, sticky=W, padx = 5, pady=1)

				self.e_SERVER_max_proc[cj] = Tkinter.Entry(Cluster_page, width=5)
				self.e_SERVER_max_proc[cj].insert(0, SERVER_max_proc[cj])
				self.e_SERVER_max_proc[cj].grid(row=cj+1, column=2, sticky=W, padx = 5, pady=1)

				self.e_SERVER_ssh_port[cj] = Tkinter.Entry(Cluster_page, width=5)
				self.e_SERVER_ssh_port[cj].insert(0, SERVER_ssh_port[cj])
				self.e_SERVER_ssh_port[cj].grid(row=cj+1, column=3, sticky=W, padx = 5, pady=1)

				self.e_SERVER_queue_name[cj] = Tkinter.Entry(Cluster_page, width=15)
				self.e_SERVER_queue_name[cj].insert(0, SERVER_queue_name[cj])
				self.e_SERVER_queue_name[cj].grid(row=cj+1, column=4, sticky=W, padx = 5, pady=1)

				self.e_SERVER_home_dir[cj] = Tkinter.Entry(Cluster_page, width=25)
				self.e_SERVER_home_dir[cj].insert(0, SERVER_home_dir[cj])
				self.e_SERVER_home_dir[cj].grid(row=cj+1, column=5, sticky=W, padx = 5, pady=1)

				self.e_SERVER_amber_dir[cj] = Tkinter.Entry(Cluster_page, width=30)
				self.e_SERVER_amber_dir[cj].insert(0, SERVER_amber_dir[cj])
				self.e_SERVER_amber_dir[cj].grid(row=cj+1, column=6, sticky=W, padx = 5, pady=1)
			else:
				var = IntVar()
				self.cb_aa[cj] = Checkbutton(Cluster_page, text=str(i+1), variable=var)
				self.cb_aa[cj].grid(row=cj+1, column=0, sticky=W, padx=5)
				self.v_aa.append(var)
				self.cb_aa[cj].deselect()

				self.e_SERVER_nodename[cj] = Tkinter.Entry(Cluster_page, width=25)
				self.e_SERVER_nodename[cj].insert(0, "")
				self.e_SERVER_nodename[cj].grid(row=cj+1, column=1, sticky=W, padx = 5, pady=1)

				self.e_SERVER_max_proc[cj] = Tkinter.Entry(Cluster_page, width=5)
				self.e_SERVER_max_proc[cj].insert(0, "")
				self.e_SERVER_max_proc[cj].grid(row=cj+1, column=2, sticky=W, padx = 5, pady=1)

				self.e_SERVER_ssh_port[cj] = Tkinter.Entry(Cluster_page, width=5)
				self.e_SERVER_ssh_port[cj].insert(0, "")
				self.e_SERVER_ssh_port[cj].grid(row=cj+1, column=3, sticky=W, padx = 5, pady=1)

				self.e_SERVER_queue_name[cj] = Tkinter.Entry(Cluster_page, width=15)
				self.e_SERVER_queue_name[cj].insert(0, "")
				self.e_SERVER_queue_name[cj].grid(row=cj+1, column=4, sticky=W, padx = 5, pady=1)

				self.e_SERVER_home_dir[cj] = Tkinter.Entry(Cluster_page, width=25)
				self.e_SERVER_home_dir[cj].insert(0, "")
				self.e_SERVER_home_dir[cj].grid(row=cj+1, column=5, sticky=W, padx = 5, pady=1)

				self.e_SERVER_amber_dir[cj] = Tkinter.Entry(Cluster_page, width=30)
				self.e_SERVER_amber_dir[cj].insert(0, "")
				self.e_SERVER_amber_dir[cj].grid(row=cj+1, column=6, sticky=W, padx = 5, pady=1)
			cj += 1
			



		nb1.pack(fill='both',expand=1,padx=5,pady=5)
		nb1.setnaturalsize()

#		self.dialog.active()
		self.dialog.activate(geometry = 'centerscreenalways')



	def reset(self, textcur, filecur):
		textcur.delete(0, END)
		textcur.insert(0, filecur)

	def writeNewFile(self):
		# path_home = os.environ.get('HOME')
		if not sys.platform.startswith('win'):
    		     home = os.environ.get('HOME')
		else:
                     home = os.environ.get('PYMOL_PATH')
		filename = "%s/Settings_Linux.txt" % home
            
		# write Settings_Linux.txt file
		fi = open(filename, "w")
		fi.write("USER:\n")
		fi.write("username                           %s\n" % username)
		fi.write("\nCLIENT:\n")
		fi.write("library_dir                        %s\n" % library_dir)
		fi.write("amber_dir                          %s\n" % amber_dir)
		fi.write("slide_main_dir                     %s\n" % slide_main_dir)
		fi.write("slide_exe_dir                      %s\n" % slide_exe_dir)
		fi.write("slide_main_dir_multiple            %s\n" % slide_main_dir_multiple)
		fi.write("slide_exe_dir_multiple             %s\n" % slide_exe_dir_multiple)
		fi.write("slide_data_dir                     %s\n" % slide_data_dir)
		fi.write("slide_dir                          %s\n" % slide_dir)
		fi.write("slide_sort                         %s\n" % slide_sort)
		fi.write("sie_dir                            %s\n" % sie_dir)
		fi.write("autodock_dir                       %s\n" % autodock_dir)
		fi.write("autodock_exe_dir                   %s\n" % autodock_exe_dir)
		fi.write("vina_dir                           %s\n" % vina_dir)
		fi.write("changepdb_dir                      %s\n" % changepdb_dir)
		fi.write("changecrd_dir                      %s\n" % changecrd_dir)
		fi.write("symposar_exe_dir                   %s\n" % symposar_exe_dir)
		fi.write("raptor_exe_dir                     %s\n" % raptor_exe_dir)
		fi.write("reduce_exe_dir                     %s\n" % reduce_exe_dir)
		fi.write("\n")
		fi.write("STANDARD SERVER SETTINGS:\n")
		fi.write("SERVER_number_of                   %d\n" % SERVER_number_of)
		fi.write("SERVER_nodename")
		for cj in range(SERVER_number_of):
			fi.write("     %s" % SERVER_nodename[cj])
		fi.write("\n")
		fi.write("SERVER_max_proc")
		for cj in range(SERVER_number_of):
			fi.write("     %s" % SERVER_max_proc[cj])
		fi.write("\n")
		fi.write("SERVER_ssh_port")
		for cj in range(SERVER_number_of):
			fi.write("     %s" % SERVER_ssh_port[cj])
		fi.write("\n")
		fi.write("SERVER_queue_name")
		for cj in range(SERVER_number_of):
			fi.write("     %s" % SERVER_queue_name[cj])
		fi.write("\n")
		fi.write("SERVER_home_dir")
		for cj in range(SERVER_number_of):
			fi.write("     %s" % SERVER_home_dir[cj])
		fi.write("\n")
		fi.write("SERVER_amber_dir")
		for cj in range(SERVER_number_of):
			fi.write("     %s" % SERVER_amber_dir[cj])
		fi.write("\n")
		fi.close()
        
	def searchFOLDER(self, filecur, textcur):
		self.folder_select = ""
		self.folder_select = askdirectory(title="Select directory", initialdir=filecur, mustexist=1)
		if self.folder_select:
			textcur.delete(0, END)
			textcur.insert(0, self.folder_select)
			filecur = self.folder_select

	def apply(self, result):
		global username
    
		global library_dir
		global amber_dir
		global gro_amb_dir
		global slide_main_dir
		global slide_exe_dir
		global slide_main_dir_multiple
		global slide_exe_dir_multiple
		global slide_data_dir
		global slide_dir
		global slide_sort
		global autodock_dir
		global autodock_exe_dir
		global vina_dir
		global sie_dir
		global changepdb_dir
		global changecrd_dir
		global symposar_exe_dir
		global raptor_exe_dir
		global reduce_exe_dir
 	   
		global SERVER_number_of
		global SERVER_nodename
		global SERVER_max_proc
		global SERVER_ssh_port
		global SERVER_queue_name
		global SERVER_home_dir
		global SERVER_amber_dir

		if result == 'Exit':
			self.dialog.deactivate()
			self.dialog.withdraw()
		elif result == 'Save to file':
			username                 = self.e_username.get()
			library_dir              = self.e_library_dir.get()
			amber_dir                = self.e_amber_dir.get()
#			gro_amb_dir              = self.e_gro_amb_dir.get()
			gro_amb_dir              = ""
			slide_main_dir           = self.e_slide_main_dir.get()
			slide_exe_dir            = self.e_slide_exe_dir.get()
			slide_main_dir_multiple  = self.e_slide_main_dir_multiple.get()
			slide_exe_dir_multiple   = self.e_slide_exe_dir_multiple.get()
			slide_data_dir           = self.e_slide_data_dir.get()
			slide_dir                = self.e_slide_dir.get()
			slide_sort               = self.e_slide_sort.get()
			sie_dir                  = self.e_sie_dir.get()
			autodock_dir             = self.e_autodock_dir.get()
			autodock_exe_dir         = self.e_autodock_exe_dir.get()
			vina_dir                 = self.e_vina_dir.get()
			changepdb_dir            = self.e_changepdb_dir.get()
			changecrd_dir            = self.e_changecrd_dir.get()
			symposar_exe_dir         = self.e_symposar_exe_dir.get()
			raptor_exe_dir           = self.e_raptor_exe_dir.get()
			reduce_exe_dir           = self.e_reduce_exe_dir.get()
			# number of clusters
			cj = 0
			for i in range(10):
				if self.v_aa[i].get() == 1:
					cj+=1
			SERVER_number_of = cj
			for cj in range(10):
				SERVER_nodename[cj] = self.e_SERVER_nodename[cj].get()
				SERVER_max_proc[cj] = self.e_SERVER_max_proc[cj].get()
				SERVER_ssh_port[cj] = self.e_SERVER_ssh_port[cj].get()
				SERVER_queue_name[cj] = self.e_SERVER_queue_name[cj].get()
				SERVER_home_dir[cj] = self.e_SERVER_home_dir[cj].get()
				SERVER_amber_dir[cj] = self.e_SERVER_amber_dir[cj].get()

			self.writeNewFile()			
		else:
			#path_home                = os.environ.get('HOME')
                        if not sys.platform.startswith('win'):
    		             path_home = os.environ.get('HOME')
		        else:
                             path_home = os.environ.get('PYMOL_PATH')
			username                 = os.getlogin()
			library_dir              = "/usr/local/AMBER_library"
			amber_dir                = "/usr/local/amber10"
			gro_amb_dir              = ""
			slide_main_dir           = "/usr/local/slide"
			slide_exe_dir            = "/usr/local/slide/bin"
			slide_main_dir_multiple  = "/usr/local/slide_all"
			slide_exe_dir_multiple   = "/usr/local/slide_all/bin"
			slide_data_dir           = "%s/slide" % path_home
			slide_dir                = "%s/SLIDE_library" % path_home
			slide_sort               = "/usr/local/sortSlideResults"
			sie_dir                  = "/usr/local/Brimm"
			autodock_dir             = "%s/AUTODOCK_library" % path_home
			autodock_exe_dir         = "/usr/local/MGLTools-1.5.4/MGLToolsPckgs/AutoDockTools/Utilities24"
			vina_dir                 = "/usr/local/autodock_vina_1_1_2_linux_x86/bin"
			changepdb_dir            = "/usr/local/Ryde/changepdb"
			changecrd_dir            = "/usr/local/Ryde/changecrd"
			symposar_exe_dir         = "/usr/local/symposar"
			raptor_exe_dir           = "/usr/local/raptor"
			reduce_exe_dir           = "/usr/local/reduce/reduce.3.14.080821.src/reduce_src"
			SERVER_number_of         = 2    
			SERVER_nodename          = ["mycluster1.myuniversity.edu", "mycluster2.myuniversity.edu", "", "", "", "", "", "", "", ""]
			SERVER_max_proc          = ["8", "32", "", "", "", "", "", "", "", ""]
			SERVER_ssh_port          = ["22", "22", "", "", "", "", "", "", "", ""]
			SERVER_queue_name          = ["queue1", "queue2", "", "", "", "", "", "", "", ""]
			SERVER_home_dir          = ["/home_on_cluster1/username", "/home_on_cluster2/username", "", "", "", "", "", "", "", ""]
			SERVER_amber_dir         = ["/application_dir_on_cluster1/amber10", "/application_dir_on_cluster2/amber10", "", "", "", "", "", "", "", ""]
			self.reset(self.e_username, username)
			self.reset(self.e_library_dir, library_dir)
			self.reset(self.e_amber_dir, amber_dir)
			self.reset(self.e_slide_main_dir, slide_main_dir)
			self.reset(self.e_slide_exe_dir, slide_exe_dir)
			self.reset(self.e_slide_main_dir_multiple, slide_main_dir_multiple)
			self.reset(self.e_slide_exe_dir_multiple, slide_exe_dir_multiple)
			self.reset(self.e_slide_data_dir, slide_data_dir)
			self.reset(self.e_slide_dir, slide_dir)
			self.reset(self.e_slide_sort, slide_sort)
			self.reset(self.e_sie_dir, sie_dir)
			self.reset(self.e_autodock_dir, autodock_dir)
			self.reset(self.e_autodock_exe_dir, autodock_exe_dir)
			self.reset(self.e_vina_dir, vina_dir)
			self.reset(self.e_changepdb_dir, changepdb_dir)
			self.reset(self.e_changecrd_dir, changecrd_dir)
			self.reset(self.e_symposar_exe_dir, symposar_exe_dir)
			self.reset(self.e_raptor_exe_dir, raptor_exe_dir)
			self.reset(self.e_reduce_exe_dir, reduce_exe_dir)
			for cj in range(SERVER_number_of):
				self.reset(self.e_SERVER_nodename[cj], SERVER_nodename[cj])
				self.reset(self.e_SERVER_max_proc[cj], SERVER_max_proc[cj])
				self.reset(self.e_SERVER_ssh_port[cj], SERVER_ssh_port[cj])
				self.reset(self.e_SERVER_queue_name[cj], SERVER_queue_name[cj])
				self.reset(self.e_SERVER_home_dir[cj], SERVER_home_dir[cj])
				self.reset(self.e_SERVER_amber_dir[cj], SERVER_amber_dir[cj])

  
#######################################################################################
def modify_settings(app):
	mfs = modifySettingsFile(app.root)


#######################################################################################
def read_settings(app):
	global username
    
	global library_dir
	global amber_dir
	global gro_amb_dir
	global slide_main_dir
	global slide_exe_dir
	global slide_main_dir_multiple
	global slide_exe_dir_multiple
	global slide_data_dir
	global slide_dir
	global slide_sort
	global autodock_dir
	global autodock_exe_dir
	global vina_dir
	global sie_dir
	global changepdb_dir
	global changecrd_dir
	global symposar_exe_dir
	global raptor_exe_dir
	global reduce_exe_dir
    
	global SERVER_number_of

	#path1 = os.environ.get('HOME')
        if not sys.platform.startswith('win'):
    	     path_home = os.environ.get('HOME')
	else:
             path_home = os.environ.get('PYMOL_PATH')
	filename = "%s/Settings_Linux.txt" % (path_home)
	try:
		fi = open(filename, "r")
	except:
		tkMessageBox.showwarning("Settings file not found", "Settings_Linux.txt not found. Please, copy download default file and copy to $HOME directory.")
		sys.exit()

#    print "Read settings for SLIDE"
	for i in fi:
		if i.find("username") == 0:
			tmpc, dat = i.split(None, 1)
			dat2 = str(dat)
			username = dat2.rstrip()

		if i.find("library_dir") == 0:
			tmpc, dat = i.split(None, 1)
			dat2 = str(dat)
			library_dir = dat2.rstrip()
		if i.find("amber_dir") == 0:
			tmpc, dat = i.split(None, 1)
			dat2 = str(dat)
			amber_dir = dat2.rstrip()
		if i.find("gro_amb_dir") == 0:
			tmpc, dat = i.split(None, 1)
			dat2 = str(dat)
			gro_amb_dir = dat2.rstrip()
		if i.find("slide_main_dir") == 0:
			tmpc, dat = i.split(None, 1)
			dat2 = str(dat)
			slide_main_dir = dat2.rstrip()
		if i.find("slide_exe_dir") == 0:
			tmpc, dat = i.split(None, 1)
			dat2 = str(dat)
			slide_exe_dir = dat2.rstrip()
		if i.find("slide_main_dir_multiple") == 0:
			tmpc, dat = i.split(None, 1)
			dat2 = str(dat)
			slide_main_dir_multiple = dat2.rstrip()
		if i.find("slide_exe_dir_multiple") == 0:
			tmpc, dat = i.split(None, 1)
			dat2 = str(dat)
			slide_exe_dir_multiple = dat2.rstrip()
		if i.find("slide_data_dir") == 0:
			tmpc, dat = i.split(None, 1)
			dat2 = str(dat)
			slide_data_dir = dat2.rstrip()
		if i.find("slide_dir") == 0:
			tmpc, dat = i.split(None, 1)
			dat2 = str(dat)
			slide_dir = dat2.rstrip()
		if i.find("slide_sort") == 0:
			tmpc, dat = i.split(None, 1)
			dat2 = str(dat)
			slide_sort = dat2.rstrip()
		if i.find("autodock_dir") == 0:
			tmpc, dat = i.split(None, 1)
			dat2 = str(dat)
			autodock_dir = dat2.rstrip()
		if i.find("autodock_exe_dir") == 0:
			tmpc, dat = i.split(None, 1)
			dat2 = str(dat)
			autodock_exe_dir = dat2.rstrip()
		if i.find("vina_dir") == 0:
			tmpc, dat = i.split(None, 1)
			dat2 = str(dat)
			vina_dir = dat2.rstrip()
		if i.find("sie_dir") == 0:
			tmpc, dat = i.split(None, 1)
			dat2 = str(dat)
			sie_dir = dat2.rstrip()
		if i.find("changepdb_dir") == 0:
			tmpc, dat = i.split(None, 1)
			dat2 = str(dat)
			changepdb_dir = dat2.rstrip()
		if i.find("changecrd_dir") == 0:
			tmpc, dat = i.split(None, 1)
			dat2 = str(dat)
			changecrd_dir = dat2.rstrip()
		if i.find("symposar_exe_dir") == 0:
			tmpc, dat = i.split(None, 1)
			dat2 = str(dat)
			symposar_exe_dir = dat2.rstrip()
		if i.find("raptor_exe_dir") == 0:
			tmpc, dat = i.split(None, 1)
			dat2 = str(dat)
			raptor_exe_dir = dat2.rstrip()
		if i.find("reduce_exe_dir") == 0:
			tmpc, dat = i.split(None, 1)
			dat2 = str(dat)
			reduce_exe_dir = dat2.rstrip()

		if i.find("SERVER_number_of") == 0:
			tmpc, dat = i.split(None, 1)
			SERVER_number_of = int(dat)

	global SERVER_nodename
	global SERVER_max_proc
	global SERVER_ssh_port
	global SERVER_queue_name
	global SERVER_home_dir
	global SERVER_amber_dir
	SERVER_nodename = ["" for i in range(10)]
	SERVER_max_proc = ["0" for i in range(10)]
	SERVER_ssh_port = ["" for i in range(10)]
	SERVER_queue_name = ["" for i in range(10)]
	SERVER_home_dir = ["" for i in range(10)]
	SERVER_amber_dir = ["" for i in range(10)]
 
	fi.seek(0)
	for i in fi:
		if i.find("SERVER_nodename") == 0:
			i2 = i.strip()
			datarray = i2.split(None)
			datarray.pop(0)
			cj = 0
			for x in datarray:
				SERVER_nodename[cj] = str(x)
				cj += 1
		if i.find("SERVER_max_proc") == 0:
			i2 = i.strip()
			datarray = i2.split(None)
			datarray.pop(0)
			cj = 0
			for x in datarray:
				SERVER_max_proc[cj] = str(x)
				cj += 1
		if i.find("SERVER_ssh_port") == 0:
			i2 = i.strip()
			datarray = i2.split(None)
			datarray.pop(0)
			cj = 0
			for x in datarray:
				SERVER_ssh_port[cj] = str(x)
				cj += 1
		if i.find("SERVER_queue_name") == 0:
			i2 = i.strip()
			datarray = i2.split(None)
			datarray.pop(0)
			cj = 0
			for x in datarray:
				SERVER_queue_name[cj] = str(x)
				cj += 1
		if i.find("SERVER_home_dir") == 0:
			i2 = i.strip()
			datarray = i2.split(None)
			datarray.pop(0)
			cj = 0
			for x in datarray:
				SERVER_home_dir[cj] = str(x)
				cj += 1
		if i.find("SERVER_amber_dir") == 0:
			i2 = i.strip()
			datarray = i2.split(None)
			datarray.pop(0)
			cj = 0
			for x in datarray:
				SERVER_amber_dir[cj] = str(x)
				cj += 1
    
	fi.close()

 
    
	readAmberLibrary(app)

#read_settings()
        
</pre><div style="position: absolute; left: 0px; top: 0px; right: 0px; bottom: 0px; visibility: hidden;"><embed id="lingoes_plugin_object" type="application/lingoes-npruntime-capture-word-plugin" hidden="true" width="0" height="0"></div></body></html>
